package com.huashi.dealer.modular.business.order.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huashi.dealer.commonEntity.*;
import com.huashi.dealer.core.component.DataScopeInfo;
import com.huashi.dealer.core.exception.CommonException;
import com.huashi.dealer.core.page.PageFactory;
import com.huashi.dealer.core.util.SaTokenUtil;
import com.huashi.dealer.core.util.TimeUtil;
import com.huashi.dealer.modular.business.address.service.AddressService;
import com.huashi.dealer.modular.business.goods.mapper.GoodsImageMapper;
import com.huashi.dealer.modular.business.goods.mapper.GoodsMapper;
import com.huashi.dealer.modular.business.goods.mapper.GoodsSkuMapper;
import com.huashi.dealer.modular.business.goods.mapper.CartMapper;
import com.huashi.dealer.modular.business.goods.service.GoodsService;
import com.huashi.dealer.modular.business.goods.service.StoreGoodsService;
import com.huashi.dealer.modular.business.message.service.MessageService;
import com.huashi.dealer.modular.business.order.enums.AuditStatusEnum;
import com.huashi.dealer.modular.business.order.mapper.OrderGoodsMapper;
import com.huashi.dealer.modular.business.upload.service.UploadService;
import com.huashi.dealer.modular.business.user.mapper.StoreUserMapper;
import com.huashi.dealer.modular.business.user.service.UserService;
import com.huashi.dealer.modular.business.setting.service.StoreSettingService;
import com.huashi.dealer.modular.business.setting.vo.FullFreeSettingVo;
import com.huashi.dealer.modular.business.order.mapper.OrderMapper;
import com.huashi.dealer.modular.business.order.mapper.StoreOrderMapper;
import com.huashi.dealer.modular.business.order.param.*;
import com.huashi.dealer.modular.business.order.service.*;
import com.huashi.dealer.modular.business.cart.service.CheckoutService;
import com.huashi.dealer.modular.business.cart.param.CartResponseParam;
import com.huashi.dealer.modular.business.discount.mapper.DiscountActiveMapper;
import com.huashi.dealer.modular.business.discount.mapper.DiscountActiveGoodsMapper;
import com.huashi.dealer.modular.business.discount.mapper.DiscountActiveSpecMapper;
import com.huashi.dealer.commonEntity.DiscountActive;
import com.huashi.dealer.commonEntity.DiscountActiveGoods;
import com.huashi.dealer.commonEntity.DiscountActiveSpec;


import com.huashi.dealer.commonEntity.OrderAddress;
import com.huashi.dealer.commonEntity.OrderGoods;
import com.huashi.dealer.commonEntity.OrderExpress;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.*;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Arrays;

import com.huashi.dealer.modular.business.user.param.UserAddressVo;

/**
 * API订单Service实现类
 *
 * @author 谭陈强
 * @since 2025-07-30
 */
@Service("apiOrderServiceImpl")
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Resource
    private StoreUserMapper storeUserMapper;
    @Resource
    private UserService userService;
    @Resource
    private UploadService uploadService;
    @Resource
    private OrderGoodsService orderGoodsService;
    @Resource
    private OrderExpressService orderExpressService;
    @Resource
    private OrderExtractService orderExtractService;
    @Resource
    private OrderAddressService orderAddressService;
    @Resource
    private MessageService messageService;
    @Resource
    private DataScopeInfo dataScopeInfo;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private StoreGoodsService storeGoodsService;
    @Autowired
    private GoodsImageMapper goodsImageMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private GoodsSkuMapper goodsSkuMapper;
    @Autowired
    private CheckoutService checkoutService;

    @Autowired
    private AddressService userAddressService;

    @Autowired
    private StoreSettingService storeSettingService;

    // 优惠活动相关Mapper注入
    @Autowired
    private DiscountActiveGoodsMapper discountActiveGoodsMapper;
    @Autowired
    private DiscountActiveMapper discountActiveMapper;
    @Autowired
    private DiscountActiveSpecMapper discountActiveSpecMapper;

    // Store端订单Mapper注入（用于活动相关查询）
    @Autowired
    private StoreOrderMapper storeOrderMapper;

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;

    @Override
    public OrderResponseParam getCartOrder(String cartIds, String payType, String source) {
        OrderResponseParam responseParam = new OrderResponseParam();

        try {
            // 解析用户ID（使用SaTokenUtil获取正确的用户ID）
            Long userId = SaTokenUtil.getLoginId();
            if (userId == null) {
                throw new CommonException("用户令牌无效或已过期");
            }

            // 解析参数
            Integer payTypeInt = payType != null ? Integer.valueOf(payType) : 10;
            Integer sourceInt = source != null ? Integer.valueOf(source) : 10;

            // 获取购物车商品列表
            List<CartResponseParam.CartGoodsInfo> goodsList = getCartGoodsList(userId, cartIds, sourceInt);

            if (goodsList.isEmpty()) {
                throw new CommonException("购物车中没有商品");
            }

            // 调用结算服务获取订单结算信息
            CartResponseParam checkoutResult = checkoutService.onCheckout(userId, goodsList);

            // 构建响应数据
            responseParam.setOrderId(null); // 这是预览，还没有创建订单
            responseParam.setOrderNo(null);
            responseParam.setTotalPrice(checkoutResult.getCartTotalPrice());
            responseParam.setOrderPrice(checkoutResult.getCartTotalPrice()); // 暂时等于总价，后续会计算优惠
            responseParam.setOrderStatus(10); // 待付款
            responseParam.setPayStatus(10); // 未支付
            responseParam.setPayType(payTypeInt);
            responseParam.setSource(sourceInt);
            responseParam.setCreateTime(LocalDateTime.now());

            // 转换商品列表格式
            List<OrderResponseParam.OrderGoodsInfo> orderGoodsList = convertToOrderGoodsInfo(goodsList);
            responseParam.setGoodsList(orderGoodsList);

            // 设置其他结算信息
            responseParam.setCouponMoney(BigDecimal.ZERO); // TODO: 计算优惠券抵扣
            responseParam.setPointsMoney(BigDecimal.ZERO); // TODO: 计算积分抵扣
            responseParam.setDeliveryMoney(BigDecimal.ZERO); // TODO: 计算运费

            log.info("获取购物车订单成功，用户ID: {}, 商品数量: {}, 总金额: {}", userId, goodsList.size(), checkoutResult.getCartTotalPrice());

        } catch (Exception e) {
            log.error("获取购物车订单失败", e);
            throw new CommonException("获取购物车订单失败：" + e.getMessage());
        }

        return responseParam;
    }

    /**
     * 提交订单（购物车结算）
     *
     * @param requestParam 请求参数
     * @return 订单信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderResponseParam submitOrder(OrderRequestParam requestParam) {
        OrderResponseParam responseParam = new OrderResponseParam();

        try {

            if (requestParam.getCartIds() == null || requestParam.getCartIds().isEmpty()) {
                throw new CommonException("购物车ID不能为空");
            }
            if (requestParam.getPayType() == null) {
                throw new CommonException("支付方式不能为空");
            }

            // 解析用户ID
            Long userId = SaTokenUtil.getLoginId();
            if (userId == null) {
                throw new CommonException("用户令牌无效或已过期");
            }

            // 获取购物车商品列表
            List<CartResponseParam.CartGoodsInfo> goodsList = getCartGoodsList(userId, requestParam.getCartIds(), requestParam.getSource());

            if (goodsList.isEmpty()) {
                throw new CommonException("购物车中没有商品");
            }

            // 调用结算服务获取订单结算信息
            CartResponseParam checkoutResult = checkoutService.onCheckout(userId, goodsList);

            // 创建订单和所有相关数据
            Order order = createOrderAndRelatedData(userId, requestParam, goodsList, checkoutResult);

            // 处理赠品商品
            if (requestParam.getMarketGoodsIds() != null && !requestParam.getMarketGoodsIds().trim().isEmpty()) {
                processMarketGoodsForOrder(order.getOrderId(), requestParam.getMarketGoodsIds(), System.currentTimeMillis() / 1000);
            }

            // 清除购物车中已下单的商品
            clearCartItems(userId, requestParam.getCartIds(), requestParam.getSource());

            // 发送订单创建消息通知
            sendOrderMessage(userId, order.getOrderNo());

            // 构建响应数据
            responseParam.setOrderId(order.getOrderId().longValue());
            responseParam.setOrderNo(order.getOrderNo());
            responseParam.setTotalPrice(order.getTotalPrice());
            responseParam.setOrderPrice(order.getOrderPrice());
            responseParam.setOrderStatus(order.getOrderStatus());
            responseParam.setPayStatus(order.getPayStatus());
            responseParam.setPayType(order.getPayType());
            responseParam.setSource(order.getOrderSource()); // 修正：使用orderSource字段
            responseParam.setCreateTime(LocalDateTime.now());

            // 转换商品列表格式
            List<OrderResponseParam.OrderGoodsInfo> orderGoodsList = convertToOrderGoodsInfo(goodsList);
            responseParam.setGoodsList(orderGoodsList);

            // 设置其他结算信息
            responseParam.setCouponMoney(order.getCouponMoney());
            responseParam.setPointsMoney(order.getPointsMoney());
            responseParam.setDeliveryMoney(order.getExpressPrice()); // 修正：使用expressPrice字段

            log.info("订单创建成功，订单号: {}, 用户ID: {}, 总金额: {}", order.getOrderNo(), userId, order.getOrderPrice());

        } catch (Exception e) {
            log.error("提交订单失败", e);
            throw new CommonException("提交订单失败：" + e.getMessage());
        }

        return responseParam;
    }

    /**
     * 从token获取用户ID
     *
     * @param token 用户令牌
     * @return 用户ID
     */
    private Long getUserIdFromToken(String token) {
        try {
            // 使用SaTokenUtil获取正确的用户ID
            return SaTokenUtil.getLoginId();
        } catch (Exception e) {
            log.error("从token获取用户ID失败", e);
            return null;
        }
    }

    /**
     * 获取购物车商品列表
     *
     * @param userId  用户ID
     * @param cartIds 购物车ID列表，格式：goods_id_goods_sku_id，多个用逗号分隔
     * @param source  订单类型：10普通订单，30返利订单，40核销订单
     * @return 购物车商品列表
     */
    private List<CartResponseParam.CartGoodsInfo> getCartGoodsList(Long userId, String cartIds, Integer source) {
        List<CartResponseParam.CartGoodsInfo> goodsList = new ArrayList<>();

        try {
            // 构建查询条件
            LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<Cart>().eq(Cart::getUserId, userId).eq(Cart::getIsGoodsType, source).eq(Cart::getIsDelete, 0);

            // 如果指定了cartIds，则按ID过滤
            if (cartIds != null && !cartIds.isEmpty()) {
                // 解析cartIds格式：goods_id_goods_sku_id，多个用逗号分隔
                String[] cartIdArray = cartIds.split(",");
                List<Long> goodsIds = new ArrayList<>();
                List<Long> goodsSkuIds = new ArrayList<>();

                for (String cartId : cartIdArray) {
                    String[] parts = cartId.split("_");
                    if (parts.length >= 2) {
                        try {
                            goodsIds.add(Long.valueOf(parts[0]));
                            goodsSkuIds.add(Long.valueOf(parts[1]));
                        } catch (NumberFormatException e) {
                            log.warn("无效的购物车ID格式: {}", cartId);
                        }
                    }
                }

                if (!goodsIds.isEmpty()) {
                    queryWrapper.in(Cart::getGoodsId, goodsIds);
                }
            }

            // 查询购物车记录
            List<Cart> cartItems = cartMapper.selectList(queryWrapper.orderByDesc(Cart::getCreateTime));

            // 验证商品类型一致性
            validateGoodsTypeConsistency(cartItems, source);

            // 获取商品信息
            for (Cart cartItem : cartItems) {
                CartResponseParam.CartGoodsInfo goodsInfo = buildCartGoodsInfo(cartItem);
                if (goodsInfo != null) {
                    goodsList.add(goodsInfo);
                }
            }

            // 检查余额是否充足（针对核销商品和返利商品）
            if (source == 30 || source == 40) { // 30返利订单，40核销订单
                checkUserBalance(userId, source, goodsList);
            }

        } catch (Exception e) {
            log.error("获取购物车商品列表失败，用户ID: {}", userId, e);
            throw new CommonException("获取购物车商品列表失败：" + e.getMessage());
        }

        return goodsList;
    }

    /**
     * 验证商品类型一致性
     *
     * @param cartItems 购物车记录列表
     * @param source    订单类型
     */
    private void validateGoodsTypeConsistency(List<Cart> cartItems, Integer source) {
        if (cartItems == null || cartItems.isEmpty()) {
            return;
        }

        // 检查所有商品的类型是否一致
        for (Cart cartItem : cartItems) {
            if (!cartItem.getIsGoodsType().equals(source)) {
                throw new CommonException("购物车商品类型不一致，不能混合结算不同类型的商品");
            }
        }

        log.debug("商品类型验证通过，所有商品类型: {}", source);
    }

    /**
     * 检查用户余额是否充足
     *
     * @param userId    用户ID
     * @param source    订单类型
     * @param goodsList 商品列表
     */
    private void checkUserBalance(Long userId, Integer source, List<CartResponseParam.CartGoodsInfo> goodsList) {
        try {
            // 获取用户信息
            User user = userService.getById(userId);
            if (user == null) {
                throw new CommonException("用户信息不存在");
            }

            // 计算商品总价
            BigDecimal totalPrice = BigDecimal.ZERO;
            for (CartResponseParam.CartGoodsInfo goods : goodsList) {
                BigDecimal goodsPrice = goods.getActivePrice() != null && goods.getActivePrice().compareTo(BigDecimal.ZERO) > 0 ? goods.getActivePrice() : goods.getGoodsPrice();
                BigDecimal goodsTotalPrice = goodsPrice.multiply(new BigDecimal(goods.getGoodsNum()));
                totalPrice = totalPrice.add(goodsTotalPrice);
            }

            // 根据订单类型检查对应余额
            if (source == 30) { // 返利订单
                BigDecimal rebateBalance = user.getRebate() != null ? user.getRebate() : BigDecimal.ZERO;
                if (totalPrice.compareTo(rebateBalance) > 0) {
                    throw new CommonException(String.format("返利余额不足，需要: %s，当前余额: %s", totalPrice, rebateBalance));
                }
                log.debug("返利余额检查通过，需要: {}, 余额: {}", totalPrice, rebateBalance);

            } else if (source == 40) { // 核销订单
                BigDecimal writeoffBalance = user.getWriteoff() != null ? user.getWriteoff() : BigDecimal.ZERO;
                if (totalPrice.compareTo(writeoffBalance) > 0) {
                    throw new CommonException(String.format("核销余额不足，需要: %s，当前余额: %s", totalPrice, writeoffBalance));
                }
                log.debug("核销余额检查通过，需要: {}, 余额: {}", totalPrice, writeoffBalance);
            }

        } catch (Exception e) {
            if (e instanceof CommonException) {
                throw e; // 重新抛出业务异常
            }
            log.error("检查用户余额失败，用户ID: {}", userId, e);
            throw new CommonException("检查用户余额失败：" + e.getMessage());
        }
    }

    /**
     * 构建购物车商品信息
     *
     * @param cartItem 购物车记录
     * @return 购物车商品信息
     */
    private CartResponseParam.CartGoodsInfo buildCartGoodsInfo(Cart cartItem) {
        try {
            // 获取商品信息
            Goods goods = goodsMapper.selectById(cartItem.getGoodsId());
            if (goods == null || goods.getIsDelete() == 1) {
                log.warn("商品不存在或已删除，商品ID: {}", cartItem.getGoodsId());
                return null;
            }

            // 获取商品SKU信息
            GoodsSku goodsSku = goodsSkuMapper.selectById(cartItem.getGoodsSkuId());
            if (goodsSku == null) {
                log.warn("商品SKU不存在，SKU ID: {}", cartItem.getGoodsSkuId());
                return null;
            }

            // 获取商品图片
            String goodsImage = "";
            if (goodsSku.getImageId() != null) {
                // 使用正确的方法获取商品图片URL
                List<String> imageUrls = goodsImageMapper.getFileUrlByGoodsId(goodsSku.getImageId());
                if (imageUrls != null && !imageUrls.isEmpty()) {
                    goodsImage = imageUrls.get(0);
                }
            }

            // 构建购物车商品信息
            CartResponseParam.CartGoodsInfo goodsInfo = new CartResponseParam.CartGoodsInfo();
            goodsInfo.setCartId(cartItem.getCartId());
            goodsInfo.setGoodsId(cartItem.getGoodsId());
            goodsInfo.setGoodsSkuId(cartItem.getGoodsSkuId());
            goodsInfo.setUserId(cartItem.getUserId()); // 设置用户ID
            goodsInfo.setGoodsName(goods.getGoodsName());
            goodsInfo.setGoodsSpec(goodsSku.getSpec()); // 修复：使用getSpec()而不是getGoodsAttr()
            goodsInfo.setGoodsPrice(goodsSku.getGoodsPrice());
            goodsInfo.setGoodsNum(cartItem.getGoodsNum());
            goodsInfo.setLinePrice(goodsSku.getLinePrice());
            goodsInfo.setStockNum(goodsSku.getStockNum());
            goodsInfo.setCategoryId(goods.getCategoryId());
            goodsInfo.setSellingPoint(goods.getSellingPoint());
            goodsInfo.setBarCode(goods.getBarCode());
            goodsInfo.setSpecType(goods.getSpecType());
            goodsInfo.setDeductStockType(goods.getDeductStockType());
            goodsInfo.setGoodsStatus(goods.getGoodsStatus());
            goodsInfo.setGoodsImage(goodsImage);
            goodsInfo.setCartCreateTime(cartItem.getCreateTime());

            // 处理活动商品逻辑
            processActiveGoods(goodsInfo, cartItem);

            // 计算商品总价 - 优先使用活动价格
            BigDecimal finalPrice = goodsInfo.getActivePrice() != null && goodsInfo.getActivePrice().compareTo(BigDecimal.ZERO) > 0 ? goodsInfo.getActivePrice() : goodsSku.getGoodsPrice();
            BigDecimal goodsTotalPrice = finalPrice.multiply(new BigDecimal(cartItem.getGoodsNum()));
            goodsInfo.setGoodsTotalPrice(goodsTotalPrice);

            return goodsInfo;

        } catch (Exception e) {
            log.error("构建购物车商品信息失败，购物车ID: {}", cartItem.getCartId(), e);
            return null;
        }
    }

    /**
     * 处理活动商品逻辑
     *
     * @param goodsInfo 商品信息
     * @param cartItem  购物车记录
     */
    private void processActiveGoods(CartResponseParam.CartGoodsInfo goodsInfo, Cart cartItem) {
        try {
            // 初始化活动商品相关字段
            goodsInfo.setIsActiveGoods(0); // 默认不参与活动
            goodsInfo.setActivePrice(BigDecimal.ZERO);
            goodsInfo.setSetNum(0);
            goodsInfo.setDiscountId(null);
            goodsInfo.setDiscountActiveStatus(null);
            goodsInfo.setNewActiveGoodsNum(0);

            // 查询商品是否参与优惠活动
            List<DiscountActiveGoods> activeGoodsList = discountActiveGoodsMapper.selectList(new LambdaQueryWrapper<DiscountActiveGoods>().eq(DiscountActiveGoods::getGoodsId, cartItem.getGoodsId()));

            if (activeGoodsList.isEmpty()) {
                return; // 商品不参与任何活动
            }

            // 获取第一个活动（假设一个商品只参与一个活动）
            DiscountActiveGoods activeGoods = activeGoodsList.get(0);
            Long discountId = activeGoods.getDiscountId();

            // 查询活动信息
            DiscountActive active = discountActiveMapper.selectById(discountId);
            if (active == null || active.getIsDelete() == 1 || active.getStatus() != 10) {
                return; // 活动不存在、已删除或未启用
            }

            // 设置活动基本信息
            goodsInfo.setDiscountId(discountId);
            goodsInfo.setDiscountActiveStatus(active.getStatus());
            goodsInfo.setActiveDiscount(active);
            goodsInfo.setActiveInfo(active);

            // 查询活动规格（起订数量）- 按num升序排列
            List<DiscountActiveSpec> activeSpecs = discountActiveSpecMapper.selectList(new LambdaQueryWrapper<DiscountActiveSpec>().eq(DiscountActiveSpec::getDiscountId, discountId).orderByAsc(DiscountActiveSpec::getNum) // 按起订数量升序
            );

            if (activeSpecs.isEmpty()) {
                return; // 没有活动规格
            }

            // 获取最小起订数量
            Integer minSetNum = activeSpecs.get(0).getNum();
            goodsInfo.setSetNum(minSetNum);

            // 检查当前商品数量是否满足最小起订数量
            if (cartItem.getGoodsNum() >= minSetNum) {
                // 满足最小起订数量，参与活动
                goodsInfo.setIsActiveGoods(1);

                DiscountActiveSpec matchedSpec = null;
                for (int i = activeSpecs.size() - 1; i >= 0; i--) {
                    DiscountActiveSpec spec = activeSpecs.get(i);
                    if (cartItem.getGoodsNum() >= spec.getNum()) {
                        matchedSpec = spec;
                        break; // 找到第一个满足条件的规格（向下取整）
                    }
                }

                if (matchedSpec != null) {
                    goodsInfo.setActivePrice(matchedSpec.getPrice());
                    goodsInfo.setSetNum(matchedSpec.getNum());

                    // 设置活动规格信息
                    Map<String, Object> activeSpecMap = new HashMap<>();
                    activeSpecMap.put("num", matchedSpec.getNum());
                    goodsInfo.setActiveSpec(activeSpecMap);

                    log.debug("商品ID: {} 参与活动，购买数量: {}，满足规格: num={}, 价格: {}", cartItem.getGoodsId(), cartItem.getGoodsNum(), matchedSpec.getNum(), matchedSpec.getPrice());
                }
            } else {
                // 未满足最小起订数量
                goodsInfo.setIsActiveGoods(2);
                goodsInfo.setActivePrice(goodsInfo.getGoodsPrice()); // 使用原价

                // 设置活动规格信息
                Map<String, Object> activeSpecMap = new HashMap<>();
                activeSpecMap.put("num", minSetNum);
                goodsInfo.setActiveSpec(activeSpecMap);

                log.debug("商品ID: {} 未满足活动起订数量，购买数量: {}，需要数量: {}", cartItem.getGoodsId(), cartItem.getGoodsNum(), minSetNum);
            }

            // 设置活动商品总数量（当前购物车中的数量）
            goodsInfo.setNewActiveGoodsNum(cartItem.getGoodsNum());

        } catch (Exception e) {
            log.error("处理活动商品逻辑失败，商品ID: {}", cartItem.getGoodsId(), e);
            // 出错时设置为不参与活动
            goodsInfo.setIsActiveGoods(0);
            goodsInfo.setActivePrice(BigDecimal.ZERO);
        }
    }

    /**
     * 转换购物车商品信息为订单商品信息
     *
     * @param cartGoodsList 购物车商品列表
     * @return 订单商品列表
     */
    private List<OrderResponseParam.OrderGoodsInfo> convertToOrderGoodsInfo(List<CartResponseParam.CartGoodsInfo> cartGoodsList) {
        List<OrderResponseParam.OrderGoodsInfo> orderGoodsList = new ArrayList<>();

        for (CartResponseParam.CartGoodsInfo cartGoods : cartGoodsList) {
            OrderResponseParam.OrderGoodsInfo orderGoods = new OrderResponseParam.OrderGoodsInfo();
            orderGoods.setGoodsId(cartGoods.getGoodsId());
            orderGoods.setGoodsSkuId(cartGoods.getGoodsSkuId());
            orderGoods.setGoodsName(cartGoods.getGoodsName());
            orderGoods.setGoodsImage(cartGoods.getGoodsImage());
            orderGoods.setGoodsSpec(cartGoods.getGoodsSpec());
            orderGoods.setGoodsNum(cartGoods.getGoodsNum());
            orderGoods.setGoodsPrice(cartGoods.getGoodsPrice());
            orderGoods.setGoodsTotalPrice(cartGoods.getGoodsTotalPrice());
            orderGoods.setCategoryId(cartGoods.getCategoryId().intValue());

            orderGoodsList.add(orderGoods);
        }

        return orderGoodsList;
    }

    /**
     * 创建订单和所有相关数据
     *
     * @param userId         用户ID
     * @param requestParam   请求参数
     * @param goodsList      商品列表
     * @param checkoutResult 结算结果
     * @return 订单对象
     */
    private Order createOrderAndRelatedData(Long userId, OrderRequestParam requestParam, List<CartResponseParam.CartGoodsInfo> goodsList, CartResponseParam checkoutResult) {
        try {
            // 1. 创建订单主记录
            Order order = new Order();
            order.setOrderNo(generateOrderNo());
            order.setUserId(userId.intValue());
            order.setTotalPrice(checkoutResult.getCartTotalPrice()); // 商品总金额(不含优惠折扣)
            order.setOrderPrice(checkoutResult.getCartTotalPrice()); // 订单金额(含优惠折扣) - 暂时等于总价，后续会计算优惠
            order.setCouponId(requestParam.getCouponId() != null ? requestParam.getCouponId().intValue() : 0);
            order.setCouponMoney(BigDecimal.ZERO); // 优惠券抵扣金额 - 后续计算
            order.setPointsMoney(BigDecimal.ZERO); // 积分抵扣金额 - 后续计算
            order.setPointsNum(requestParam.getPointsNum() != null ? requestParam.getPointsNum() : 0);
            order.setPayPrice(checkoutResult.getCartTotalPrice()); // 实际付款金额(包含运费) - 暂时等于总价
            order.setUpdatePrice(BigDecimal.ZERO); // 后台修改的订单金额（差价）
            order.setBuyerRemark(requestParam.getRemark() != null ? requestParam.getRemark() : "");
            order.setPayType(requestParam.getPayType() != null ? requestParam.getPayType() : 20); // 支付方式(10余额支付 20微信支付)
            order.setPayStatus(10); // 付款状态(10未付款 20已付款)
            order.setPayTime(0L); // 付款时间
            order.setDeliveryType(10); // 配送方式(10快递配送 20上门自提)
            order.setExtractShopId(0); // 自提门店id
            order.setExtractClerkId(0); // 核销店员id
            order.setExpressPrice(BigDecimal.ZERO); // 运费金额 - 后续计算
            order.setExpressId(0); // 物流公司id
            order.setExpressCompany(""); // 物流公司
            order.setExpressNo(""); // 物流单号
            order.setDeliveryStatus(10); // 发货状态(10未发货 20已发货 30部分发货)
            order.setReceiptStatus(10); // 收货状态(10未收货 20已收货)
            order.setReceiptTime(0L); // 收货时间
            order.setOrderStatus(10); // 订单状态(10进行中 20取消 21待取消 30已完成)
            order.setAuditStatus(30); // 审核状态（0待审核，10已驳回，20已通过，30初审待审核，40初审已驳回，50初审已通过）
            order.setRejectReason(""); // 驳回原因
            order.setPointsBonus(0); // 赠送的积分数量
            order.setIsSettled(0); // 订单是否已结算(0未结算 1已结算)
            order.setTransactionId(""); // 微信支付交易号
            order.setIsComment(0); // 是否已评价(0否 1是)
            order.setOrderSource(requestParam.getSource() != null ? requestParam.getSource() : 10); // 订单来源(10普通订单 20砍价订单 30秒杀订单)
            order.setOrderSourceId(0); // 来源记录id
            order.setIsDelete(0); // 是否删除
            order.setWxappId(10001); // 小程序id - 根据实际情况设置
            order.setCreateTime((System.currentTimeMillis() / 1000)); // 创建时间
            order.setUpdateTime((System.currentTimeMillis() / 1000)); // 更新时间

            // 保存订单
            this.save(order);

            // 2. 创建订单商品记录
            createOrderGoods(order.getOrderId(), goodsList, userId);

            // 3. 创建订单地址记录（如果有收货地址）
            if (requestParam.getAddressId() != null && requestParam.getAddressId() != 0) {
                createOrderAddress(order.getOrderId(), Long.valueOf(userService.getById(userId).getAddressId()));
            } else {
                createOrderAddress(order.getOrderId(), requestParam.getAddressId());
            }

            // 4. 更新商品库存
            updateGoodsStock(goodsList);

            // 5. 处理优惠券（如果有）
            if (requestParam.getCouponId() != null) {
                processCouponUsage(requestParam.getCouponId(), userId);
            }

            // 6. 处理积分抵扣（如果有）
            if (requestParam.getPointsNum() != null && requestParam.getPointsNum() > 0) {
                processPointsDeduction(userId, requestParam.getPointsNum(), order.getOrderNo());
            }

            log.info("订单创建完成，订单ID: {}, 订单号: {}", order.getOrderId(), order.getOrderNo());
            return order;

        } catch (Exception e) {
            log.error("创建订单失败，用户ID: {}", userId, e);
            throw new CommonException("创建订单失败：" + e.getMessage());
        }
    }

    /**
     * 创建订单商品记录
     *
     * @param orderId   订单ID
     * @param goodsList 商品列表
     */
    private void createOrderGoods(Integer orderId, List<CartResponseParam.CartGoodsInfo> goodsList, Long userId) {
        List<OrderGoods> orderGoodsList = new ArrayList<>();

        for (CartResponseParam.CartGoodsInfo goods : goodsList) {
            OrderGoods orderGoods = new OrderGoods();

            // 基础信息
            orderGoods.setOrderId(orderId);
            orderGoods.setGoodsId(goods.getGoodsId().intValue());
            orderGoods.setGoodsName(goods.getGoodsName());
            List<GoodsImage> goodsImages = goodsImageMapper.selectList(new LambdaQueryWrapper<GoodsImage>().eq(GoodsImage::getGoodsId, goods.getGoodsId()));
            if(goodsImages != null && goodsImages.size() > 0) {
                orderGoods.setImageId(goodsImages.get(0).getImageId().intValue());
            }
            orderGoods.setDeductStockType(goods.getDeductStockType() != null ? goods.getDeductStockType() : 20);
            orderGoods.setSpecType(goods.getSpecType() != null ? goods.getSpecType() : 10);
            orderGoods.setSpecSkuId(goods.getGoodsSkuId().toString());
            orderGoods.setGoodsSkuId(goods.getGoodsSkuId().intValue());
            orderGoods.setGoodsSkuSpec(goods.getGoodsSpec());
            orderGoods.setGoodsAttr(goods.getGoodsSpec()); // 商品规格信息

            // 商品详情和编码
            orderGoods.setContent(""); // 商品详情 - 暂时为空
            orderGoods.setGoodsNo(goods.getBarCode() != null ? goods.getBarCode() : "");
            orderGoods.setBarCode(goods.getBarCode());

            // 价格信息
            orderGoods.setGoodsPrice(goods.getGoodsPrice());
            orderGoods.setGoodsMoney(goods.getGoodsPrice()); // 商品单价
            orderGoods.setLinePrice(goods.getLinePrice() != null ? goods.getLinePrice() : goods.getGoodsPrice());
            orderGoods.setGoodsWeight(0.0); // 商品重量 - 暂时设为0

            // 会员折扣相关
            orderGoods.setIsUserGrade(0);
            orderGoods.setGradeRatio(0);
            orderGoods.setGradeGoodsPrice(BigDecimal.ZERO);
            orderGoods.setGradeTotalMoney(BigDecimal.ZERO);

            // 优惠券和积分
            orderGoods.setCouponMoney(BigDecimal.ZERO);
            orderGoods.setPointsMoney(BigDecimal.ZERO);
            orderGoods.setPointsNum(0);
            orderGoods.setPointsBonus(0);

            // 活动价格
            orderGoods.setDiscountActivePrice(goods.getActivePrice() != null ? goods.getActivePrice() : BigDecimal.ZERO);

            // 数量和价格
            orderGoods.setTotalNum(goods.getGoodsNum());
            orderGoods.setTotalPrice(goods.getGoodsTotalPrice());
            orderGoods.setTotalPayPrice(goods.getGoodsTotalPrice()); // 实际付款价暂时等于总价

            // 分销相关
            orderGoods.setIsIndDealer(0);
            orderGoods.setDealerMoneyType(10);
            orderGoods.setFirstMoney(BigDecimal.ZERO);
            orderGoods.setSecondMoney(BigDecimal.ZERO);
            orderGoods.setThirdMoney(BigDecimal.ZERO);

            // 状态信息
            orderGoods.setIsComment(0);
            orderGoods.setUserId(userId.intValue()); // 使用传入的userId参数
            orderGoods.setGoodsSourceId(0);
            orderGoods.setWxappId(10001);
            orderGoods.setIsType(10); // 10商品，20赠品
            orderGoods.setIsOrderExpress(10); // 10未发货，20已发货
            orderGoods.setOrderExpressId(0);
            orderGoods.setIsDelete(0);

            // 时间信息
            orderGoods.setCreateTime(System.currentTimeMillis() / 1000);

            orderGoodsList.add(orderGoods);
        }

        orderGoodsService.saveBatch(orderGoodsList);
    }

    /**
     * 创建订单地址记录
     *
     * @param orderId   订单ID
     * @param addressId 地址ID
     */
    private void createOrderAddress(Integer orderId, Long addressId) {
        try {
            // 获取用户地址信息
            UserAddress userAddress = userAddressService.getById(addressId);
            if (userAddress != null) {
                OrderAddress orderAddress = new OrderAddress();
                orderAddress.setOrderId(orderId);
                orderAddress.setName(userAddress.getName());
                orderAddress.setPhone(userAddress.getPhone());
                orderAddress.setDetail(userAddress.getDetail());
                orderAddress.setCreateTime(System.currentTimeMillis() / 1000);
                orderAddress.setCityId(userAddress.getCityId());
                orderAddress.setProvinceId(userAddress.getProvinceId());
                orderAddress.setRegionId(userAddress.getRegionId());
                orderAddress.setUserId(userAddress.getUserId());

                orderAddressService.save(orderAddress);
            }
        } catch (Exception e) {
            log.warn("创建订单地址记录失败，订单ID: {}, 地址ID: {}", orderId, addressId, e);
        }
    }

    /**
     * 更新商品库存
     *
     * @param goodsList 商品列表
     */
    private void updateGoodsStock(List<CartResponseParam.CartGoodsInfo> goodsList) {
        try {
            for (CartResponseParam.CartGoodsInfo goods : goodsList) {
                // 更新商品SKU库存
                LambdaUpdateWrapper<GoodsSku> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(GoodsSku::getGoodsSkuId, goods.getGoodsSkuId()).setSql("stock_num = stock_num - " + goods.getGoodsNum());

                goodsSkuMapper.update(null, updateWrapper);
            }
            log.debug("商品库存更新完成，商品数量: {}", goodsList.size());
        } catch (Exception e) {
            log.warn("更新商品库存失败", e);
        }
    }

    /**
     * 更新商品库存（立即购买场景）
     *
     * @param goodsList 商品列表
     */
    private void updateGoodsStockForBuyNow(List<OrderResponseParam.OrderGoodsInfo> goodsList) {
        try {
            for (OrderResponseParam.OrderGoodsInfo goods : goodsList) {
                // 更新商品SKU库存
                LambdaUpdateWrapper<GoodsSku> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(GoodsSku::getGoodsSkuId, goods.getGoodsSkuId()).setSql("stock_num = stock_num - " + goods.getGoodsNum());

                goodsSkuMapper.update(null, updateWrapper);
            }
            log.debug("立即购买商品库存更新完成，商品数量: {}", goodsList.size());
        } catch (Exception e) {
            log.warn("立即购买更新商品库存失败", e);
        }
    }

    /**
     * 处理优惠券使用
     *
     * @param couponId 优惠券ID
     * @param userId   用户ID
     */
    private void processCouponUsage(Long couponId, Long userId) {
        try {
            // TODO: 实现优惠券使用逻辑
            // 1. 验证优惠券是否可用
            // 2. 更新优惠券使用状态
            // 3. 计算优惠券抵扣金额
            log.debug("优惠券使用处理，优惠券ID: {}, 用户ID: {}", couponId, userId);
        } catch (Exception e) {
            log.warn("处理优惠券使用失败，优惠券ID: {}, 用户ID: {}", couponId, userId, e);
        }
    }

    /**
     * 处理积分抵扣
     *
     * @param userId    用户ID
     * @param pointsNum 积分数量
     * @param orderNo   订单号
     */
    private void processPointsDeduction(Long userId, Integer pointsNum, String orderNo) {
        try {
            // TODO: 实现积分抵扣逻辑
            // 1. 验证用户积分是否充足
            // 2. 扣除用户积分
            // 3. 记录积分使用日志
            log.debug("积分抵扣处理，用户ID: {}, 积分数量: {}, 订单号: {}", userId, pointsNum, orderNo);
        } catch (Exception e) {
            log.warn("处理积分抵扣失败，用户ID: {}, 积分数量: {}", userId, pointsNum, e);
        }
    }

    /**
     * 清除购物车中已下单的商品
     *
     * @param userId  用户ID
     * @param cartIds 购物车ID列表
     * @param source  订单类型
     */
    private void clearCartItems(Long userId, String cartIds, Integer source) {
        try {
            if (cartIds == null || cartIds.isEmpty()) {
                return;
            }

            // 解析购物车ID
            String[] cartIdArray = cartIds.split(",");
            List<Long> goodsIds = new ArrayList<>();
            List<Long> goodsSkuIds = new ArrayList<>();

            for (String cartId : cartIdArray) {
                String[] parts = cartId.split("_");
                if (parts.length >= 2) {
                    try {
                        goodsIds.add(Long.valueOf(parts[0]));
                        goodsSkuIds.add(Long.valueOf(parts[1]));
                    } catch (NumberFormatException e) {
                        log.warn("无效的购物车ID格式: {}", cartId);
                    }
                }
            }

            if (!goodsIds.isEmpty()) {
                // 删除购物车记录
                LambdaQueryWrapper<Cart> deleteWrapper = new LambdaQueryWrapper<>();
                deleteWrapper.eq(Cart::getUserId, userId).eq(Cart::getIsGoodsType, source).in(Cart::getGoodsId, goodsIds);

                int deletedCount = cartMapper.delete(deleteWrapper);
                log.info("购物车商品清理完成，用户ID: {}, 删除数量: {}", userId, deletedCount);
            }
        } catch (Exception e) {
            log.error("清除购物车商品失败，用户ID: {}", userId, e);
            // 这里不抛出异常，因为订单已经创建成功，购物车清理失败不应该影响订单
        }
    }

    /**
     * 发送订单创建消息通知
     *
     * @param userId  用户ID
     * @param orderNo 订单号
     */
    private void sendOrderMessage(Long userId, String orderNo) {
        try {
            // 创建消息记录
            Message message = new Message();
            message.setUserId(userId.intValue());
            message.setMessageTitle("经销商下单通知");
            String formattedTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            message.setMessageContent("您于 " + formattedTime + " 下单成功，订单号为：" + orderNo);
            message.setIsType(30); // 订单消息类型
            message.setStatus(0); // 未读
            message.setCreateTime(System.currentTimeMillis() / 1000);
            message.setUpdateTime(System.currentTimeMillis() / 1000);

            messageService.save(message);
            log.debug("订单消息通知发送成功，用户ID: {}, 订单号: {}", userId, orderNo);
        } catch (Exception e) {
            log.warn("发送订单消息通知失败，用户ID: {}, 订单号: {}", userId, orderNo, e);
        }
    }

    /**
     * 生成订单号
     *
     * @return 订单号
     */
    private String generateOrderNo() {
        return LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")) +
                String.format("%03d", new Random().nextInt(1000));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderResponseParam buyNow(OrderRequestParam requestParam) {
        OrderResponseParam responseParam = new OrderResponseParam();

        try {
            // 校验：cartIds参数必填
            if (requestParam.getCartIds() == null || requestParam.getCartIds().isEmpty()) {
                throw new CommonException("cartIds参数不能为空");
            }

            Long userId = SaTokenUtil.getLoginId();
            if (userId == null) {
                throw new CommonException("用户未登录或登录已过期");
            }

            Integer payType = requestParam.getPayType() != null ? requestParam.getPayType() : 10;

            // 查询详情与库存校验
            List<OrderResponseParam.OrderGoodsInfo> goodsDetailList = new ArrayList<>();
            java.util.Set<Integer> goodsTypeSet = new java.util.HashSet<>(); // 10商品，20赠品

            // 解析 cartIds: goodsId_goodsSkuId_num[,goodsId_goodsSkuId_num]
            List<OrderResponseParam.OrderGoodsInfo> parsedList = new ArrayList<>();
            for (String part : requestParam.getCartIds().split(",")) {
                String s = part.trim();
                if (s.isEmpty()) continue;
                String[] arr = s.split("_");
                if (arr.length != 3) {
                    throw new CommonException("cartIds参数格式错误:" + s + "，正确格式应为：goodsId_goodsSkuId_num");
                }
                try {
                    OrderResponseParam.OrderGoodsInfo info = new OrderResponseParam.OrderGoodsInfo();
                    info.setGoodsId(Long.parseLong(arr[0]));
                    info.setGoodsSkuId(Long.parseLong(arr[1]));
                    info.setGoodsNum(Integer.parseInt(arr[2]));
                    parsedList.add(info);
                } catch (NumberFormatException ne) {
                    throw new CommonException("cartIds参数格式错误:" + s + "，必须是数字格式");
                }
            }
            if (parsedList.isEmpty()) {
                throw new CommonException("cartIds参数解析后无有效商品");
            }

            // 查询详情与库存校验（支持多个商品）
            for (OrderResponseParam.OrderGoodsInfo parsedGoods : parsedList) {
                Goods goods = goodsMapper.selectById(parsedGoods.getGoodsId());
                if (goods == null || (goods.getIsDelete() != null && goods.getIsDelete() == 1)) {
                    throw new CommonException("商品不存在或已删除: " + parsedGoods.getGoodsId());
                }
                goodsTypeSet.add(goods.getIsType() != null ? goods.getIsType() : 10);

                GoodsSku sku = goodsSkuMapper.selectById(parsedGoods.getGoodsSkuId());
                if (sku == null) {
                    throw new CommonException("商品规格不存在: " + parsedGoods.getGoodsSkuId());
                }
                if (sku.getStockNum() == null || sku.getStockNum() < parsedGoods.getGoodsNum()) {
                    throw new CommonException("商品库存不足: " + goods.getGoodsName());
                }

                List<String> imageUrls = goodsImageMapper.getFileUrlByGoodsId(parsedGoods.getGoodsId());
                OrderResponseParam.OrderGoodsInfo goodsInfo = new OrderResponseParam.OrderGoodsInfo();
                goodsInfo.setGoodsTotalPrice(requestParam.getTotalPrice());
                goodsInfo.setGoodsImage(imageUrls.isEmpty() ? "" : imageUrls.get(0));
                goodsInfo.setGoodsName(goods.getGoodsName());
                goodsInfo.setGoodsPrice(sku.getGoodsPrice());
                goodsInfo.setGoodsNum(parsedGoods.getGoodsNum());
                goodsInfo.setGoodsSpec(sku.getSpec());
                goodsInfo.setGoodsId(parsedGoods.getGoodsId());
                goodsInfo.setCategoryId(goods.getCategoryId().intValue());
                goodsInfo.setGoodsSkuId(parsedGoods.getGoodsSkuId());
                goodsDetailList.add(goodsInfo);
            }
            // 活动匹配与活动价计算（对同一活动分组，累计数量后按阶梯价计算）
            applyDiscountActiveForBuyNow(goodsDetailList);

            // 以活动价优先计算每行与订单金额
            // 计算金额
            BigDecimal totalPrice = goodsDetailList.stream().map(g -> {
                BigDecimal unit = g.getGoodsPrice();
                // 如果设置了活动价且大于0，则使用活动价
                if (g.getGoodsTotalPrice() == null) {
                    // 兜底：如果之前未设置行总价，这里按当前单价计算
                    return unit.multiply(new BigDecimal(g.getGoodsNum()));
                }
                return g.getGoodsTotalPrice();
            }).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal orderPrice = totalPrice;

            // 创建订单
            Order order = new Order();
            order.setOrderNo(generateOrderNo());
            order.setUserId(userId.intValue());
            order.setOrderStatus(10);
            order.setPayStatus(10);
            order.setPayType(payType);
            order.setTotalPrice(totalPrice);
            order.setOrderPrice(orderPrice);
            order.setIsDelete(0);
            order.setBuyerRemark(requestParam.getRemark());
            order.setPayPrice(totalPrice);
            order.setWxappId(10001);
            order.setAuditStatus(AuditStatusEnum.FIRST_PENDING.getValue());
            long now = System.currentTimeMillis() / 1000;
            order.setCreateTime(now);
            order.setUpdateTime(now);
            this.save(order);

            // 保存订单商品
            for (OrderResponseParam.OrderGoodsInfo it : goodsDetailList) {
                OrderGoods og = new OrderGoods();
                og.setOrderId(order.getOrderId());
                og.setGoodsId(it.getGoodsId().intValue());
                og.setGoodsName(it.getGoodsName());
                og.setGoodsSkuId(it.getGoodsSkuId().intValue());
                og.setGoodsSkuSpec(it.getGoodsSpec());
                og.setSpecSkuId(String.valueOf(it.getGoodsSkuId()));
                og.setGoodsAttr(it.getGoodsSpec());
                og.setContent("");
                og.setGoodsPrice(it.getGoodsPrice());
                og.setGoodsMoney(it.getGoodsPrice());
                og.setTotalNum(it.getGoodsNum());
                BigDecimal rowTotal = it.getGoodsTotalPrice() != null ? it.getGoodsTotalPrice() : it.getGoodsPrice().multiply(new BigDecimal(it.getGoodsNum()));
                og.setTotalPrice(rowTotal);
                og.setTotalPayPrice(rowTotal);

                // 读取商品与SKU以补齐更多字段
                Goods goodsEntity = goodsMapper.selectById(it.getGoodsId());
                GoodsSku skuEntity = goodsSkuMapper.selectById(it.getGoodsSkuId());
                List<GoodsImage> goodsImages = goodsImageMapper.selectList(new LambdaQueryWrapper<GoodsImage>().eq(GoodsImage::getGoodsId, it.getGoodsId()));
                if(goodsImages != null && goodsImages.size() > 0) {
                    og.setImageId(goodsImages.get(0).getImageId().intValue());
                }
                if (skuEntity != null) {

                    og.setSpecSkuId(skuEntity.getSpecSkuId());
                    og.setGoodsNo(skuEntity.getGoodsNo());
                    og.setGoodsWeight(skuEntity.getGoodsWeight());
                    og.setLinePrice(skuEntity.getLinePrice());
                }
                if (goodsEntity != null) {
                    og.setDeductStockType(goodsEntity.getDeductStockType());
                    og.setSpecType(goodsEntity.getSpecType());
                    og.setBarCode(goodsEntity.getBarCode());
                    og.setIsIndDealer(goodsEntity.getIsIndDealer());
                    og.setDealerMoneyType(goodsEntity.getDealerMoneyType());
                    og.setFirstMoney(goodsEntity.getFirstMoney());
                    og.setSecondMoney(goodsEntity.getSecondMoney());
                    og.setThirdMoney(goodsEntity.getThirdMoney());
                    og.setIsType(goodsEntity.getIsType());
                }
                // 订单维度与默认值
                og.setUserId(order.getUserId());
                og.setIsOrderExpress(10); // 未发货
                og.setIsComment(0);
                og.setCouponMoney(java.math.BigDecimal.ZERO);
                og.setPointsMoney(java.math.BigDecimal.ZERO);
                og.setPointsNum(0);
                og.setPointsBonus(0);
                // 若存在活动价，记录活动单价
                if (it.getGoodsNum() != null && it.getGoodsNum() > 0) {
                    java.math.BigDecimal unitPay = rowTotal.divide(new java.math.BigDecimal(it.getGoodsNum()), 2, java.math.RoundingMode.HALF_UP);
                    if (unitPay != null && it.getGoodsPrice() != null && unitPay.compareTo(it.getGoodsPrice()) != 0) {
                        og.setDiscountActivePrice(unitPay);
                    }
                }
                og.setIsDelete(0);
                og.setCreateTime(now);
                orderGoodsService.save(og);
            }

            // 处理赠品商品
            if (requestParam.getMarketGoodsIds() != null && !requestParam.getMarketGoodsIds().trim().isEmpty()) {
                processMarketGoodsForOrder(order.getOrderId(), requestParam.getMarketGoodsIds(), now);
            }

            // 扣减商品库存
            updateGoodsStockForBuyNow(goodsDetailList);

            // 生成订单地址（取用户默认地址）
            try {
                User user = userService.getById(userId);
                if (requestParam.getAddressId() != null && requestParam.getAddressId() != 0) {
                    createOrderAddress(order.getOrderId(), requestParam.getAddressId());
                }else{
                    createOrderAddress(order.getOrderId(), Long.valueOf(user.getAddressId()));
                }
            } catch (Exception ignore) {
                log.warn("创建订单地址失败(忽略)，用户ID: {}", userId);
            }

            // 发送订单创建消息通知
            sendOrderMessage(userId, order.getOrderNo());

            // 返回
            responseParam.setOrderId(order.getOrderId().longValue());
            responseParam.setOrderNo(order.getOrderNo());
            responseParam.setTotalPrice(totalPrice);
            responseParam.setOrderPrice(orderPrice);
            responseParam.setOrderStatus(order.getOrderStatus());
            responseParam.setPayStatus(order.getPayStatus());
            responseParam.setPayType(order.getPayType());
            responseParam.setCreateTime(LocalDateTime.now());
            responseParam.setGoodsList(goodsDetailList);

            return responseParam;

        } catch (Exception e) {
            throw new CommonException("立即购买失败：" + e.getMessage());
        }
    }

    /**
     * 买Now场景：匹配活动并设置活动价/总价
     * 规则：同一活动(discount_id)内的商品按累计数量寻找阶梯价
     */
    private void applyDiscountActiveForBuyNow(List<OrderResponseParam.OrderGoodsInfo> goodsList) {
        if (goodsList == null || goodsList.isEmpty()) return;

        // 1) 找到每个商品所属的活动
        List<Long> goodsIds = goodsList.stream().map(OrderResponseParam.OrderGoodsInfo::getGoodsId).distinct().collect(Collectors.toList());
        List<DiscountActiveGoods> activeGoodsList = discountActiveGoodsMapper.selectList(new LambdaQueryWrapper<DiscountActiveGoods>().in(DiscountActiveGoods::getGoodsId, goodsIds));
        if (activeGoodsList == null || activeGoodsList.isEmpty()) {
            // 没有活动，直接设置行总价 = 原价 * 数量
            for (OrderResponseParam.OrderGoodsInfo g : goodsList) {
                g.setGoodsTotalPrice(g.getGoodsPrice().multiply(new BigDecimal(g.getGoodsNum())));
            }
            return;
        }

        // 2) 构建 goodsId -> discountId 映射（一个商品参与一个活动的假设）
        Map<Long, Long> goodsIdToDiscountId = new HashMap<>();
        for (DiscountActiveGoods ag : activeGoodsList) {
            goodsIdToDiscountId.putIfAbsent(ag.getGoodsId(), ag.getDiscountId());
        }

        // 3) 按活动分组商品
        Map<Long, List<OrderResponseParam.OrderGoodsInfo>> discountToItems = new HashMap<>();
        for (OrderResponseParam.OrderGoodsInfo g : goodsList) {
            Long did = goodsIdToDiscountId.get(g.getGoodsId());
            if (did != null) {
                discountToItems.computeIfAbsent(did, k -> new ArrayList<>()).add(g);
            }
        }

        // 4) 对每个活动组，计算累计数量并查找阶梯价
        for (Map.Entry<Long, List<OrderResponseParam.OrderGoodsInfo>> entry : discountToItems.entrySet()) {
            Long discountId = entry.getKey();
            List<OrderResponseParam.OrderGoodsInfo> items = entry.getValue();

            DiscountActive active = discountActiveMapper.selectById(discountId);
            if (active == null || (active.getIsDelete() != null && active.getIsDelete() == 1) || active.getStatus() == null || active.getStatus() != 10) {
                // 活动不可用，按原价计算
                for (OrderResponseParam.OrderGoodsInfo g : items) {
                    g.setGoodsTotalPrice(g.getGoodsPrice().multiply(new BigDecimal(g.getGoodsNum())));
                }
                continue;
            }

            int totalNum = items.stream().map(OrderResponseParam.OrderGoodsInfo::getGoodsNum).reduce(0, Integer::sum);

            List<DiscountActiveSpec> specs = discountActiveSpecMapper.selectList(new LambdaQueryWrapper<DiscountActiveSpec>().eq(DiscountActiveSpec::getDiscountId, discountId).orderByAsc(DiscountActiveSpec::getNum));

            BigDecimal appliedPrice = null;
            int appliedNum = 0;
            if (specs != null && !specs.isEmpty()) {
                // 找到满足的最大档位
                for (int i = specs.size() - 1; i >= 0; i--) {
                    DiscountActiveSpec spec = specs.get(i);
                    if (totalNum >= spec.getNum()) {
                        appliedPrice = spec.getPrice();
                        appliedNum = spec.getNum();
                        break;
                    }
                }
            }

            for (OrderResponseParam.OrderGoodsInfo g : items) {
                BigDecimal unit = (appliedPrice != null && appliedPrice.compareTo(BigDecimal.ZERO) > 0) ? appliedPrice : g.getGoodsPrice();
                g.setGoodsTotalPrice(unit.multiply(new BigDecimal(g.getGoodsNum())));
            }
        }

        // 5) 对未参与任何活动的商品，按原价计算
        for (OrderResponseParam.OrderGoodsInfo g : goodsList) {
            if (g.getGoodsTotalPrice() == null) {
                g.setGoodsTotalPrice(g.getGoodsPrice().multiply(new BigDecimal(g.getGoodsNum())));
            }
        }
    }

    @Override
    public OrderResponseParam submitOrder2(OrderRequestParam requestParam) {
        OrderResponseParam responseParam = new OrderResponseParam();

        try {
            // 验证必填字段
            if (requestParam.getToken() == null || requestParam.getToken().isEmpty()) {
                throw new CommonException("用户令牌不能为空");
            }
            if (requestParam.getCartIds() == null || requestParam.getCartIds().isEmpty()) {
                throw new CommonException("购物车ID不能为空");
            }
            if (requestParam.getPayType() == null) {
                throw new CommonException("支付方式不能为空");
            }

            // TODO: 提交订单逻辑
            // 这里需要注入OrderMapper并创建订单

            // 模拟提交订单
            responseParam.setOrderId(1L);
            responseParam.setOrderNo("ORD" + System.currentTimeMillis());
            responseParam.setTotalPrice(new BigDecimal("2000.00"));
            responseParam.setOrderPrice(new BigDecimal("2000.00"));
            responseParam.setOrderStatus(10);
            responseParam.setPayStatus(10);
            responseParam.setPayType(requestParam.getPayType());
            responseParam.setCreateTime(LocalDateTime.now());

            // 设置商品列表
            List<OrderResponseParam.OrderGoodsInfo> goodsList = new ArrayList<>();
            OrderResponseParam.OrderGoodsInfo goods = new OrderResponseParam.OrderGoodsInfo();
            goods.setGoodsId(1L);
            goods.setGoodsSkuId(1L);
            goods.setGoodsName("测试商品");
            goods.setGoodsImage("https://example.com/goods.jpg");
            goods.setGoodsSpec("规格：默认");
            goods.setGoodsNum(2);
            goods.setGoodsPrice(new BigDecimal("1000.00"));
            goods.setGoodsTotalPrice(new BigDecimal("2000.00"));
            goodsList.add(goods);
            responseParam.setGoodsList(goodsList);

        } catch (Exception e) {
            throw new CommonException("提交订单失败：" + e.getMessage());
        }

        return responseParam;
    }

    @Override
    public Page<OrderListVo> getOrderList(String dataType, Integer source, Integer time, Page<Order> page) {
        Page<OrderListVo> responseParam = PageFactory.defaultPage();
        List<OrderListVo> listVo = new ArrayList<>();

        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();

        List<Long> filter = dataScopeInfo.getUserIds();
        if (CollectionUtils.isEmpty(filter)) {
            return responseParam;
        }
        queryWrapper.in(Order::getUserId, filter);

        /** source 枚举 PayType pay_type字段*/
        queryWrapper.eq(source != null && source != 0, Order::getPayType, source);

        /** time 枚举 TimeType create_time字段*/
        queryWrapper = checkTime(time, queryWrapper);
        /** dataType 处理*/
        queryWrapper = filterDataType(dataType, queryWrapper);
        queryWrapper.orderByDesc(Order::getCreateTime);
        Page<Order> orderPage = this.page(page, queryWrapper);
        responseParam.setTotal(orderPage.getTotal());
        responseParam.setCurrent(orderPage.getCurrent());
        responseParam.setSize(orderPage.getSize());
        responseParam.setPages(orderPage.getPages());
        List<Order> list = orderPage.getRecords();

        if (CollectionUtils.isEmpty(list)) {
            return responseParam;
        }


        list.stream().forEach(order -> {
            OrderListVo orderVo = new OrderListVo();
            BeanUtil.copyProperties(order, orderVo);
            User user = userService.getById(order.getUserId());
//            orderVo=formot(order,orderVo);
            orderVo.setUser(user);

            List<OrderGoods> list1 = orderGoodsService.list(new LambdaQueryWrapper<OrderGoods>().eq(OrderGoods::getOrderId, order.getOrderId()));
            List<OrderGoodsVo> goodsList = new ArrayList<>();
            list1.stream().forEach(orderGoods -> {
                OrderGoodsVo orderGoodsVo = new OrderGoodsVo();
                BeanUtil.copyProperties(orderGoods, orderGoodsVo);
                orderGoodsVo.setCreateTimeFormat(TimeUtil.changeToLocalDateTime(orderGoods.getCreateTime()));
                UploadFile file = uploadService.getById(orderGoods.getImageId());
                orderGoodsVo.setImage(file);
                // 设置已发货数量
                Integer totalCheckNum = getDeliveredQuantity(orderGoods.getOrderId(), orderGoods.getGoodsId());
                orderGoodsVo.setTotalCheckNum(totalCheckNum);
                goodsList.add(orderGoodsVo);
            });
            orderVo.setGoodsList(goodsList);
            listVo.add(orderVo);
        });
        responseParam.setRecords(listVo);
        return responseParam;
    }


    private LambdaQueryWrapper<Order> checkTime(Integer time, LambdaQueryWrapper<Order> queryWrapper) {
        LocalDateTime startTime = null;
        LocalDateTime endTime = null;
        if (time == null || time == 0) {
            return queryWrapper;
        }
        switch (time) {
            case 10: // 当月
                startTime = LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
                endTime = LocalDateTime.now().withDayOfMonth(1).plusMonths(1).minusDays(1).withHour(23).withMinute(59).withSecond(59).withNano(0);
                break;
            case 20: // 季度
                int currentMonth = LocalDateTime.now().getMonthValue();
                int quarterStartMonth = ((currentMonth - 1) / 3) * 3 + 1;
                startTime = LocalDateTime.now().withMonth(quarterStartMonth).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
                endTime = startTime.plusMonths(3).minusSeconds(1);
                break;
            case 30: // 年度
                startTime = LocalDateTime.now().withDayOfYear(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
                endTime = startTime.plusYears(1).minusSeconds(1);
                break;
            default:
                return queryWrapper;
        }
        // 转为int时间戳（秒），假设东八区
        int startTimestamp = (int) startTime.toEpochSecond(java.time.ZoneOffset.ofHours(8));
        int endTimestamp = (int) endTime.toEpochSecond(java.time.ZoneOffset.ofHours(8));

        log.info("时间范围：{} - {} (timestamp: {} - {})", startTime, endTime, startTimestamp, endTimestamp);
        // 用int时间戳做查询
        queryWrapper.between(Order::getCreateTime, startTimestamp, endTimestamp);
        return queryWrapper;
    }

    private LambdaQueryWrapper<Order> filterDataType(String dataType, LambdaQueryWrapper<Order> queryWrapper) {
        switch (dataType) {
            case "all": //全部订单
                if (dataScopeInfo.identity() == 1) {
                    queryWrapper.ne(Order::getAuditStatus, 30);
                }
                break;
            case "audit": //审核中
                if (dataScopeInfo.identity() == 1) { // 业务员
                    queryWrapper.and(querys -> querys.and(inner -> inner.eq(Order::getOrderStatus, 10).eq(Order::getAuditStatus, 0)).or().eq(Order::getOrderStatus, 21));
                } else { // 经销商
                    queryWrapper.and(querys -> querys.and(inner1 -> inner1.and(inner2 -> inner2.eq(Order::getAuditStatus, 0).eq(Order::getOrderStatus, 10)).or(inner3 -> inner3.eq(Order::getAuditStatus, 30).eq(Order::getOrderStatus, 10))).or().eq(Order::getOrderStatus, 21));
                }
                break;
            case "reject": //驳回
                queryWrapper.eq(Order::getPayStatus, 10) // PayStatusEnum::PENDING 对应值
                        .eq(Order::getAuditStatus, 10);
                break;
            case "delivery": //待发货
                queryWrapper.eq(Order::getPayStatus, 20) // PayStatusEnum::SUCCESS 对应值
                        .eq(Order::getDeliveryStatus, 10).eq(Order::getOrderStatus, 10).eq(Order::getAuditStatus, 20);
                break;
            case "received": //待收货
                queryWrapper.eq(Order::getPayStatus, 20) // PayStatusEnum::SUCCESS 对应值
                        .eq(Order::getDeliveryStatus, 20).eq(Order::getReceiptStatus, 10).eq(Order::getOrderStatus, 10).eq(Order::getAuditStatus, 20);
                break;
            case "partorder": //部分发货
                queryWrapper.eq(Order::getPayStatus, 20) // PayStatusEnum::SUCCESS 对应值
                        .eq(Order::getDeliveryStatus, 30).eq(Order::getReceiptStatus, 10).eq(Order::getOrderStatus, 10).eq(Order::getAuditStatus, 20);
                break;
            case "comment": //已完成
                queryWrapper.eq(Order::getIsComment, 0).eq(Order::getOrderStatus, 30).eq(Order::getAuditStatus, 20);
                break;
        }
        return queryWrapper;
    }

    @Override
    public OrderDetailVo getOrderDetail(Long orderId) {
        OrderDetailVo responseParam = new OrderDetailVo();
        try {
            if (orderId == null) {
                throw new CommonException("订单ID不能为空");
            }
            Order order = this.getById(orderId);
            BeanUtil.copyProperties(order, responseParam);

            List<OrderGoods> orderGoodsList = orderGoodsService.list(new LambdaQueryWrapper<OrderGoods>().eq(OrderGoods::getOrderId, order.getOrderId()));
            List<OrderGoodsVo> goodsList = new ArrayList<>();
            orderGoodsList.stream().forEach(orderGoods -> {
                OrderGoodsVo orderGoodsVo = new OrderGoodsVo();
                BeanUtil.copyProperties(orderGoods, orderGoodsVo);
                UploadFile file = uploadService.getById(orderGoods.getImageId());
                orderGoodsVo.setImage(file);
                // 设置已发货数量
                Integer totalCheckNum = getDeliveredQuantity(orderGoods.getOrderId(), orderGoods.getGoodsId());
                orderGoodsVo.setTotalCheckNum(totalCheckNum);
                goodsList.add(orderGoodsVo);
            });
            /** 细分普通商品和赠品*/
            List<OrderGoodsVo> goodsList1 = goodsList.stream().filter(goods -> goods.getIsType() != null && goods.getIsType() == 10).collect(Collectors.toList());

            List<OrderGoodsVo> goodsList2 = goodsList.stream().filter(goods -> goods.getIsType() == null || goods.getIsType() == 20).collect(Collectors.toList());
            responseParam.setGoodsList(goodsList1);
            responseParam.setMarketGoodsList(goodsList2);
            responseParam.setOrderAddress(baseMapper.getOrderAddress(orderId));
            responseParam.setOrderExpress(orderExpressService.getOne(new LambdaQueryWrapper<OrderExpress>().eq(OrderExpress::getOrderId, orderId).last("LIMIT 1")));
            responseParam.setOrderExtract(orderExtractService.getOne(new LambdaQueryWrapper<OrderExtract>().eq(OrderExtract::getOrderId, orderId).last("LIMIT 1")));
        } catch (Exception e) {
            throw new CommonException("获取订单详情失败：" + e.getMessage());
        }

        return responseParam;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(Long orderId) {
        try {
            if (orderId == null) {
                throw new CommonException("订单ID不能为空");
            }

            // 获取订单详情
            Order order = this.getById(orderId.intValue());
            if (order == null) {
                throw new CommonException("订单不存在");
            }

            // 验证订单状态 - 已发货订单不可取消
            if (order.getDeliveryStatus() != null && order.getDeliveryStatus() == 20) {
                throw new CommonException("已发货订单不可取消");
            }

            // 判断订单是否已支付
            boolean isPay = order.getPayStatus() != null && order.getPayStatus() == 20;
            // 未付款的订单需要回退资源
            if (!isPay) {
                // 回退商品库存
                backGoodsStock(orderId);
                // 回退用户优惠券
                if (order.getCouponId() != null && order.getCouponId() > 0) {
                    backUserCoupon(order.getCouponId().longValue());
                }

                // 回退用户积分
                if (order.getPointsNum() != null && order.getPointsNum() > 0) {
                    backUserPoints(SaTokenUtil.getLoginId(), order.getPointsNum(), "订单取消：" + order.getOrderNo());
                }
            }
            // 更新订单状态
            LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Order::getOrderId, orderId.intValue()).set(Order::getOrderStatus, isPay ? 21 : 20) // 21待取消，20已取消
                    .set(Order::getUpdateTime, (int) (System.currentTimeMillis() / 1000));

            boolean success = this.update(updateWrapper);
            if (!success) {
                throw new CommonException("订单状态更新失败");
            }

        } catch (Exception e) {
            throw new CommonException("取消订单失败：" + e.getMessage());
        }
    }

    /**
     * 回退商品库存
     */
    private void backGoodsStock(Long orderId) {
        try {
            // 获取订单商品列表
            List<OrderGoods> orderGoodsList = orderGoodsService.getOrderGoodsByOrderId(orderId.intValue());
            if (orderGoodsList == null || orderGoodsList.isEmpty()) {
                return;
            }

            for (OrderGoods orderGoods : orderGoodsList) {
                // 根据库存计算方式决定是否回退
                if (orderGoods.getDeductStockType() != null && orderGoods.getDeductStockType() == 10) {
                    // 下单减库存的商品需要回退
                    orderGoodsService.backGoodsStock(orderGoods);
                }
            }
        } catch (Exception e) {
            log.error("回退商品库存失败：", e);
            throw new CommonException("回退商品库存失败：" + e.getMessage());
        }
    }

    /**
     * 回退用户优惠券
     */
    private void backUserCoupon(Long couponId) {
        try {
            // TODO: 实现优惠券回退逻辑
            // 这里需要注入UserCouponMapper并更新优惠券状态
            // UserCoupon userCoupon = new UserCoupon();
            // userCoupon.setUserCouponId(couponId);
            // userCoupon.setIsUse(false);
            // userCouponMapper.updateById(userCoupon);

            log.info("回退用户优惠券：{}", couponId);
        } catch (Exception e) {
            log.error("回退用户优惠券失败：", e);
            throw new CommonException("回退用户优惠券失败：" + e.getMessage());
        }
    }

    /**
     * 回退用户积分
     */
    private void backUserPoints(Long userId, Integer pointsNum, String describe) {
        try {
            // TODO: 实现积分回退逻辑
            // 这里需要注入UserMapper和PointsLogMapper
            // 1. 更新用户积分
            // User user = new User();
            // user.setUserId(userId);
            // user.setPoints(user.getPoints() + pointsNum);
            // userMapper.updateById(user);

            // 2. 添加积分记录
            // PointsLog pointsLog = new PointsLog();
            // pointsLog.setUserId(userId);
            // pointsLog.setPoints(pointsNum);
            // pointsLog.setDescription(describe);
            // pointsLog.setCreateTime(LocalDateTime.now());
            // pointsLogMapper.insert(pointsLog);

            log.info("回退用户积分：用户ID={}, 积分={}, 描述={}", userId, pointsNum, describe);
        } catch (Exception e) {
            log.error("回退用户积分失败：", e);
            throw new CommonException("回退用户积分失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditOrder(Long orderId, Integer auditStatus, String rejectReason) {
        try {
            if (orderId == null) {
                throw new CommonException("订单ID不能为空");
            }
            if (auditStatus == null) {
                throw new CommonException("审核状态不能为空");
            }

            // 获取订单详情
            Order order = this.getById(orderId.intValue());
            if (order == null) {
                throw new CommonException("订单不存在");
            }

            // 验证已发货订单不可审核
            if (order.getDeliveryStatus() != null && order.getDeliveryStatus() == 20) {
                throw new CommonException("已发货订单不可审核");
            }

            // 获取用户信息
            User userInfo = userService.getById(order.getUserId());


            if (userInfo == null) {
                throw new CommonException("用户信息不存在");
            }

            // 根据审核状态处理
            Integer orderStatus = null;
            String messageTitle = "订单审核通知";
            String messageContent = "";
            Boolean isPay = false;
            if (auditStatus == 10) {
                // 审核未通过
                orderStatus = 20; // 订单状态设为取消
                LocalDateTime createTime = LocalDateTime.ofEpochSecond(order.getCreateTime(), 0, java.time.ZoneOffset.ofHours(8));
                String formattedTime = createTime.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

                messageContent = String.format("您%s下的订单审核未通过，请修改订单或联系您的业务员，订单号[%s]", formattedTime, order.getOrderNo());

                if (rejectReason != null && !rejectReason.isEmpty()) {
                    messageContent += "，未通过原因：" + rejectReason;
                }

                // 如果已付款，需要退款和回退资源
                if (order.getPayStatus() != null && order.getPayStatus() == 20) {
                    // TODO: 执行退款操作
                    // refundService.executeRefund(order);

                    // 回退商品库存
                    backGoodsStock(orderId);

                    // 回退用户优惠券
                    if (order.getCouponId() != null && order.getCouponId() > 0) {
                        backUserCoupon(order.getCouponId().longValue());
                    }

                    // 回退用户积分
                    if (order.getPointsNum() != null && order.getPointsNum() > 0) {
                        backUserPoints(userInfo.getUserId(), order.getPointsNum(), "订单取消：" + order.getOrderNo());
                    }
                }
            } else if (auditStatus == 20) {
                // 审核通过
                orderStatus = 10; // 订单状态设为进行中
                isPay=true;
                LocalDateTime createTime = LocalDateTime.ofEpochSecond(order.getCreateTime(), 0, java.time.ZoneOffset.ofHours(8));
                String formattedTime = createTime.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                messageContent = String.format("您于%s下的订单审核已通过，订单号[%s]", formattedTime, order.getOrderNo());

                LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
                // TODO: 验证支付方式
                // 如果使用返利支付，验证返利余额
                if (order.getPayType() != null && order.getPayType() == 30) {
                    // TODO: 验证返利余额
                    if (userInfo.getRebate().compareTo(order.getPayPrice()) < 0) {
                        throw new CommonException("返利余额不足，无法使用返利支付");
                    }
                    updateWrapper.set(User::getRebate, userInfo.getRebate().subtract(order.getPayPrice()));
                }

                // 如果使用核销支付，验证核销余额
                if (order.getPayType() != null && order.getPayType() == 40) {
                    // TODO: 验证核销余额
                    if (userInfo.getWriteoff().compareTo(order.getPayPrice()) < 0) {
                        throw new CommonException("核销余额不足，无法使用核销支付");
                    }
                    updateWrapper.set(User::getWriteoff, userInfo.getWriteoff().subtract(order.getPayPrice()));
                }
                if (order.getPayType() != null && (order.getPayType() != 50 && order.getPayType() != 40)) {
                    updateWrapper.set(User::getBalance, userInfo.getBalance().subtract(order.getPayPrice()));
                }
                updateWrapper.eq(User::getUserId, userInfo.getUserId());
                userService.update(updateWrapper);

            } else {
                throw new CommonException("无效的审核状态");
            }

            // TODO: 发送消息通知
            Message message = new Message();
            message.setMessageContent(messageContent);
            message.setMessageTitle(messageTitle);
            message.setUserId(order.getUserId());
            message.setIsType(30);
            message.setCreateTime(System.currentTimeMillis() / 1000);
            messageService.sendMessage(message);
            log.info("发送订单审核消息：用户ID={}, 标题={}, 内容={}", order.getUserId(), messageTitle, messageContent);

            // 更新订单状态
            LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Order::getOrderId, orderId.intValue()).set(Order::getAuditStatus, auditStatus).set(Order::getAuditTime, (int) (System.currentTimeMillis() / 1000)).set(Order::getUpdateTime, (int) (System.currentTimeMillis() / 1000));

            if (orderStatus != null) {
                updateWrapper.set(Order::getOrderStatus, orderStatus);
            }
            if(isPay){
                updateWrapper.set(Order::getPayStatus, 20);
                updateWrapper.set(Order::getPayTime, (int) (System.currentTimeMillis() / 1000));
            }
            if (rejectReason != null && !rejectReason.isEmpty()) {
                updateWrapper.set(Order::getRejectReason, rejectReason);
            }

            boolean success = this.update(updateWrapper);
            if (!success) {
                throw new CommonException("订单状态更新失败");
            }

        } catch (Exception e) {
            throw new CommonException("订单审核失败：" + e.getMessage());
        }
    }

    @Override
    public void confirmOrder(Long orderId, String token) {
        try {
            if (orderId == null) {
                throw new CommonException("订单ID不能为空");
            }
            if (token == null || token.isEmpty()) {
                throw new CommonException("用户令牌不能为空");
            }

            // TODO: 确认收货
            // 这里需要注入OrderMapper并更新数据库

            // 模拟确认收货
            System.out.println("确认收货：" + orderId);

        } catch (Exception e) {
            throw new CommonException("确认收货失败：" + e.getMessage());
        }
    }

    @Override
    public void deleteOrder(Long orderId, String token) {
        try {
            if (orderId == null) {
                throw new CommonException("订单ID不能为空");
            }
            if (token == null || token.isEmpty()) {
                throw new CommonException("用户令牌不能为空");
            }

            // TODO: 删除订单
            // 这里需要注入OrderMapper并删除数据库记录

            // 模拟删除订单
            System.out.println("删除订单：" + orderId);

        } catch (Exception e) {
            throw new CommonException("删除订单失败：" + e.getMessage());
        }
    }

    @Override
    public OrderResponseParam payOrder(Long orderId, OrderRequestParam requestParam) {
        OrderResponseParam responseParam = new OrderResponseParam();

        try {
            if (orderId == null) {
                throw new CommonException("订单ID不能为空");
            }
            if (requestParam.getToken() == null || requestParam.getToken().isEmpty()) {
                throw new CommonException("用户令牌不能为空");
            }
            if (requestParam.getPayType() == null) {
                throw new CommonException("支付方式不能为空");
            }

            // TODO: 订单支付
            // 这里需要调用支付接口并更新订单状态

            // 模拟支付信息
            OrderResponseParam.PaymentInfo payment = new OrderResponseParam.PaymentInfo();
            payment.setPayType("微信支付");
            payment.setPayAmount(new BigDecimal("1000.00"));
            payment.setPayTime(LocalDateTime.now());
            payment.setPayStatus("支付成功");

            responseParam.setPayment(payment);
            responseParam.setOrderId(orderId);
            responseParam.setPayType(requestParam.getPayType());

        } catch (Exception e) {
            throw new CommonException("订单支付失败：" + e.getMessage());
        }

        return responseParam;
    }

    @Override
    public OrderResponseParam getOrderStatistics(String token) {
        // TODO: 实现订单统计逻辑
        return new OrderResponseParam();
    }

    @Override
    public Page<OrderExpressVo> getOrderExpress(Long orderId, Page<OrderExpress> page) {
        Page<OrderExpressVo> responseParam = new Page<>();
        List<OrderExpressVo> recordsList = new ArrayList<>();
        try {

            // 获取订单详情，验证订单是否存在
            Order order = this.getById(orderId);
            if (order == null) {
                throw new CommonException("订单不存在");
            }


            // 查询订单发货明细（分页查询）
            Page<OrderExpress> orderExpressPage = orderExpressService.getOrderExpressList(page, orderId);

            // 如果没有发货明细，返回空分页结果
            if (orderExpressPage == null || orderExpressPage.getRecords().isEmpty()) {
                responseParam.setRecords(new ArrayList<>());
                responseParam.setTotal(0L);
                responseParam.setCurrent(page.getCurrent());
                responseParam.setSize(page.getSize());
                return responseParam;
            }
            responseParam.setTotal(orderExpressPage.getTotal());
            responseParam.setCurrent(orderExpressPage.getCurrent());
            responseParam.setSize(orderExpressPage.getSize());

            List<OrderExpress> records = orderExpressPage.getRecords();

            if (!records.isEmpty()) {
                for (OrderExpress record : records) {
                    OrderExpressVo orderExpressVo = new OrderExpressVo();
                    BeanUtil.copyProperties(record, orderExpressVo);
                    List<OrderGoodsVo> orderGoodsList = new ArrayList<>();
                    Integer[] images = parseIntegerArray(record.getImages());
                    List<UploadFile> list = uploadService.list(new LambdaQueryWrapper<UploadFile>().in(UploadFile::getFileId, images));
                    orderExpressVo.setImagesValue(list);
                    List<String> goodsIdList = Arrays.stream(record.getGoodsId().split(",")).map(String::trim) // 去除空格
                            .collect(Collectors.toList());
                    List<Goods> goodsList = goodsService.list(new LambdaQueryWrapper<Goods>().in(Goods::getGoodsId, goodsIdList));
                    goodsList.stream().forEach(goods -> {
                        OrderGoodsVo orderGoodsVo = new OrderGoodsVo();
                        BeanUtil.copyProperties(goods, orderGoodsVo);
                        orderGoodsVo.setImageList(goodsImageMapper.getFileByGoodsId(goods.getGoodsId()));
                        orderGoodsList.add(orderGoodsVo);
                    });
                    orderExpressVo.setOrderGoodsVo(orderGoodsList);
                    recordsList.add(orderExpressVo);
                }
            }
            log.info("订单发货明细：" + records);
        } catch (Exception e) {
            throw new CommonException("获取物流信息失败：" + e.getMessage());
        }
        responseParam.setRecords(recordsList);
        return responseParam;
    }


    public String[] parseStringArray(String input) {
        // 去除方括号
        String content = input.replaceAll("[\\[\\]]", "").trim();
        if (content.isEmpty()) {
            return new String[0];
        }

        // 分割并去除每个元素的空格
        String[] parts = content.split(",");
        for (int i = 0; i < parts.length; i++) {
            parts[i] = parts[i].trim();
        }
        return parts;
    }

    public Integer[] parseIntegerArray(String input) {
        if (input == null || input.trim().isEmpty()) {
            return new Integer[0];
        }

        try {
            // 处理转义字符：去除转义的双引号
            String unescaped = input.replace("\\\"", "\"");
            log.debug("处理转义字符后: {}", unescaped);

            // 去除方括号和引号
            String content = unescaped.replaceAll("[\\[\\]\"]", "").trim();
            log.debug("去除方括号和引号后: {}", content);

            if (content.isEmpty()) {
                return new Integer[0];
            }

            // 分割并去除每个元素的空格，然后转换为Integer数组
            return Arrays.stream(content.split(",")).map(String::trim).filter(s -> !s.isEmpty()).map(Integer::valueOf).toArray(Integer[]::new);

        } catch (NumberFormatException e) {
            log.error("数字转换失败，输入: {}, 错误: {}", input, e.getMessage());
            return new Integer[0];
        } catch (Exception e) {
            log.error("解析失败，输入: {}, 错误: {}", input, e.getMessage());
            return new Integer[0];
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmReceipt(Long orderId, Integer status, String orderExpressId) {
        try {
            // 验证订单ID
            if (orderId == null) {
                throw new CommonException("订单ID不能为空");
            }

//            // 验证收货状态
//            if (status == null || status != 20) {
//                throw new CommonException("收货状态无效，应为全部收货");
//            }

            // 查询订单详情
            Order order = this.getById(orderId);
            if (order == null) {
                throw new CommonException("订单不存在");
            }

            // TODO: 验证用户权限（如果需要）
            // 可以通过token获取用户信息，然后验证订单是否属于该用户
            Order order2 = this.getById(orderId);

            if (order2.getUserId().equals(SaTokenUtil.getLoginId())) {
                throw new CommonException("无权限操作此订单");
            }

            // 验证订单状态
            // 条件1: 订单必须已发货
            if (order.getDeliveryStatus() == null || order.getDeliveryStatus() != 20) {
                throw new CommonException("订单未发货，无法确认收货");
            }

            // 条件2: 订单必须未收货
            if (order.getReceiptStatus() == null || order.getReceiptStatus() != 10) {
                throw new CommonException("订单已收货或状态不合法");
            }
            // 检查订单状态
            if (order.getOrderStatus() != 10) {
                throw new CommonException("订单状态异常，无法审核");
            }

            if (order.getDeliveryStatus() != 20) {
                throw new CommonException("未完全发货订单无法收货");
            }
            // 更新订单状态
            LambdaUpdateWrapper<Order> orderUpdateWrapper = new LambdaUpdateWrapper<>();
            orderUpdateWrapper.eq(Order::getOrderId, orderId.intValue()).set(Order::getReceiptStatus, 20).set(Order::getReceiptTime, (int) (System.currentTimeMillis() / 1000)).set(Order::getOrderStatus, 30) // 订单状态设为已完成
                    .set(Order::getUpdateTime, (int) (System.currentTimeMillis() / 1000));

            boolean orderUpdateSuccess = this.update(orderUpdateWrapper);
            if (!orderUpdateSuccess) {
                throw new CommonException("订单状态更新失败");
            }

            // 更新物流状态（如果指定了物流ID）
            if (orderExpressId != null && !orderExpressId.isEmpty()) {
                updateOrderExpressReceiptStatus(orderExpressId);
            }

            // 执行订单完成后的操作（如果是全部收货）
            if (status == 20) {
                executeOrderCompleteLogic(order);
            }

        } catch (Exception e) {
            throw new CommonException("确认收货失败：" + e.getMessage());
        }
    }

    /**
     * 更新物流收货状态
     */
    private void updateOrderExpressReceiptStatus(String orderExpressId) {
        try {
            String[] expressIds = orderExpressId.split(",");
            List<Integer> expressIdList = new ArrayList<>();

            for (String expressId : expressIds) {
                if (!expressId.trim().isEmpty()) {
                    expressIdList.add(Integer.valueOf(expressId.trim()));
                }
            }

            if (!expressIdList.isEmpty()) {
                LambdaUpdateWrapper<OrderExpress> expressUpdateWrapper = new LambdaUpdateWrapper<>();
                expressUpdateWrapper.in(OrderExpress::getOrderExpressId, expressIdList).set(OrderExpress::getReceiptStatus, 20) // 已收货
                        .set(OrderExpress::getReceiptTime, (int) (System.currentTimeMillis() / 1000));

                orderExpressService.update(expressUpdateWrapper);
            }
        } catch (Exception e) {
            log.warn("更新物流收货状态失败: {}", e.getMessage());
            // 不抛出异常，因为这不是核心功能
        }
    }

    /**
     * 执行订单完成后的业务逻辑
     */
    private void executeOrderCompleteLogic(Order order) {
        try {
            // TODO: 实现订单完成后的业务逻辑
            // 1. 计算用户积分
            // 2. 更新商品销量
            // 3. 发送通知消息
            // 4. 其他业务逻辑
            Message message = new Message();
            message.setMessageTitle("订单完成");
            message.setMessageContent("你已确认收货,订单" + order.getOrderNo() + "已完成");
            message.setIsType(30);
            message.setUserId(order.getUserId());
            message.setCreateTime(System.currentTimeMillis() / 1000);
            message.setUpdateTime(System.currentTimeMillis() / 1000);
            messageService.sendMessage(message);
            log.info("订单{}已完成，执行后续业务逻辑", order.getOrderId());

        } catch (Exception e) {
            log.error("执行订单完成逻辑失败: {}", e.getMessage());
            // 不抛出异常，因为这不是核心功能
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void salesmanCancel(Long orderId, Integer status,String rejectReason) {
        try {
            // 验证订单ID
            if (orderId == null) {
                throw new CommonException("订单ID不能为空");
            }

            // 验证状态
            if (status == null || (status != 10 && status != 20)) {
                throw new CommonException("状态无效，应为10（驳回）或20（同意取消）");
            }


            // 查询订单详情
            Order order = this.getById(orderId);
            if (order == null) {
                throw new CommonException("订单不存在");
            }

            // 验证订单状态：已发货订单不可取消
            if (order.getDeliveryStatus() != null && order.getDeliveryStatus() == 20) {
                throw new CommonException("已发货订单不可取消");
            }

            // 判断订单是否已支付
            boolean isPay = order.getPayStatus() != null && order.getPayStatus() == 20;

            // 准备更新数据
            LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Order::getOrderId, orderId.intValue()).set(Order::getRejectReason, rejectReason).set(Order::getOrderStatus, status).set(Order::getUpdateTime, (int) (System.currentTimeMillis() / 1000));

            // 如果是同意取消（status == 20）
            if (status == 20) {
                // 发送消息通知
                sendOrderCancelMessage(order);

                // 执行退款操作（如果已支付）
                if (isPay) {
                    executeRefund(order);
                }

                // 回退商品库存
                backGoodsStock(orderId);

                // 回退用户优惠券
                if (order.getCouponId() != null && order.getCouponId() > 0) {
                    backUserCoupon(order.getCouponId().longValue());
                }

                // 回退用户积分
                if (order.getPointsNum() != null && order.getPointsNum() > 0) {
                    backUserPoints(Long.valueOf(order.getUserId()), order.getPointsNum(), "订单取消：" + order.getOrderNo());
                }

                // 如果是待审核订单，同步取消
                if (order.getAuditStatus() != null && order.getAuditStatus() == 0) {
                    updateWrapper.set(Order::getAuditStatus, 10).set(Order::getAuditTime, (int) (System.currentTimeMillis() / 1000)).set(Order::getRejectReason, "订单同步取消");
                }
            }

            // 更新订单状态
            boolean success = this.update(updateWrapper);
            if (!success) {
                throw new CommonException("订单状态更新失败");
            }

        } catch (Exception e) {
            throw new CommonException("业务员取消订单失败：" + e.getMessage());
        }
    }

    /**
     * 发送订单取消消息
     */
    private void sendOrderCancelMessage(Order order) {
        try {
            LocalDateTime createTime = LocalDateTime.ofEpochSecond(order.getCreateTime(), 0, java.time.ZoneOffset.ofHours(8));
            String formattedTime = createTime.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            Message message = new Message();
            message.setMessageTitle("订单审核通知");
            message.setMessageContent(String.format("您于%s下的订单已取消，订单号[%s]", formattedTime, order.getOrderNo()));
            message.setUserId(order.getUserId());
            message.setIsType(30);

            messageService.sendMessage(message);
            log.info("发送订单取消消息：用户ID={}, 订单号={}", order.getUserId(), order.getOrderNo());

        } catch (Exception e) {
            log.error("发送订单取消消息失败: {}", e.getMessage());
            // 不抛出异常，因为这不是核心功能
        }
    }

    /**
     * 执行退款操作
     */
    private void executeRefund(Order order) {
        try {
            // TODO: 实现退款逻辑
            // 这里需要调用退款服务
            log.info("执行退款操作：订单ID={}, 退款金额={}", order.getOrderId(), order.getPayPrice());

        } catch (Exception e) {
            log.error("执行退款操作失败: {}", e.getMessage());
            // 不抛出异常，因为这不是核心功能
        }
    }

    @Override
    public CartOrderPreviewResponseParam getCartOrderPreview(String cartIds, Integer isGoodsType, Integer payType, Integer source) {
        try {
            log.info("获取购物车订单预览，cartIds: {}, isGoodsType: {}, payType: {}, source: {}", cartIds, isGoodsType, payType, source);

            // 获取当前用户ID
            Long userId = SaTokenUtil.getLoginId();
            if (userId == null) {
                throw new CommonException("用户令牌无效或已过期");
            }

            // 获取购物车商品列表（对应PHP的CartModel::getList方法）
            List<CartOrderPreviewResponseParam.CartGoodsInfo> goodsList = getCartGoodsListForPreview(userId, cartIds, isGoodsType);

            // 处理活动商品信息（对应PHP的Cart::discount_active方法）
            processActiveGoodsInfo(goodsList);

            if (goodsList.isEmpty()) {
                throw new CommonException("购物车中没有商品");
            }

            // 直接实现PHP的Checkout::onCheckout逻辑，不调用checkoutService

            // 构建返回参数（对应PHP的Checkout::checkout方法返回的数据结构）
            CartOrderPreviewResponseParam responseParam = new CartOrderPreviewResponseParam();

            // 设置商品列表
            responseParam.setGoodsList(goodsList);

            // 计算商品总数量
            int orderTotalNum = goodsList.stream().mapToInt(goods -> goods.getTotalNum() != null ? goods.getTotalNum() : 0).sum();
            responseParam.setOrderTotalNum(orderTotalNum);

            // 计算订单总金额（不含优惠折扣）
            BigDecimal orderTotalPrice = goodsList.stream().map(goods -> goods.getTotalPrice() != null ? goods.getTotalPrice() : BigDecimal.ZERO).reduce(BigDecimal.ZERO, BigDecimal::add);
            responseParam.setOrderTotalPrice(orderTotalPrice);

            // 设置配送信息（对应PHP的setOrderExpress方法）
            responseParam.setDelivery(10); // 默认快递配送
            responseParam.setExpressPrice(BigDecimal.ZERO); // 运费计算逻辑待实现
            responseParam.setIntraRegion(true); // 配送范围检查逻辑待实现

            // 设置地址信息（对应PHP的getOrderData方法中的地址处理）
//            UserAddressVo defaultAddress = userService.getDefaultAddress(userId);
//            log.info("userID={},地址是:{}",userId,defaultAddress);
            User byId = userService.getById(userId);
            UserAddress defaultAddress = userAddressService.getById(byId.getAddressId());

            responseParam.setExistAddress(defaultAddress != null);
            responseParam.setAddress(defaultAddress);

            // 设置支付方式
            responseParam.setPayType(payType != null ? payType : 10);

            // 设置积分相关（对应PHP的setOrderPoints方法）
            responseParam.setIsAllowPoints(false); // 积分抵扣设置待实现
            responseParam.setIsUsePoints(false);
            responseParam.setPointsMoney(BigDecimal.ZERO); // 积分抵扣计算逻辑待实现
            responseParam.setPointsBonus(0); // 积分赠送计算逻辑待实现

            // 设置优惠信息（对应PHP的setOrderCouponMoney和setOrderGoodsGradeMoney方法）
            responseParam.setCouponMoney(BigDecimal.ZERO); // 优惠券抵扣计算逻辑待实现
            responseParam.setGradeMoney(BigDecimal.ZERO); // 会员折扣计算逻辑待实现
            responseParam.setOrderPayPrice(orderTotalPrice); // 最终付款金额计算逻辑待实现

            // 设置系统设置（对应PHP的SettingModel::getItem('store')）
            CartOrderPreviewResponseParam.SystemSetting setting = new CartOrderPreviewResponseParam.SystemSetting();
            setting.setDelivery(Arrays.asList(10, 20)); // 支持快递配送和自提
            setting.setPointsName("积分");
            setting.setPointsDescribe("购物可获得积分");
            setting.setOrderSubmsg(new ArrayList<>());
            responseParam.setSetting(setting);

            // 设置满赠商品信息（对应PHP的marketGoodsList方法）
            List<Object> marketGoodsList = getMarketGoodsList(orderTotalPrice, null);
            responseParam.setMarketGoodsList(marketGoodsList);

            // 设置满减设置信息
            FullFreeSettingVo fullFreeSetting = storeSettingService.getFullFreeSetting();
            responseParam.setFullFree(fullFreeSetting);

            responseParam.setCouponList(new ArrayList<>()); // 可用优惠券列表逻辑待实现
            responseParam.setHasError(false);
            responseParam.setErrorMsg("");
            responseParam.setExtractShop(null); // 自提门店信息逻辑待实现
            responseParam.setLastExtract(null); // 记忆的自提联系方式逻辑待实现

            log.info("购物车订单预览获取成功，用户ID: {}, 商品数量: {}, 总金额: {}", userId, goodsList.size(), orderTotalPrice);

            return responseParam;

        } catch (Exception e) {
            log.error("获取购物车订单预览失败", e);
            throw new CommonException("获取购物车订单预览失败：" + e.getMessage());
        }
    }

    /**
     * 处理活动商品信息（对应PHP的Cart::discount_active方法）
     * 这个方法现在主要用于批量处理，单个商品的活动信息在buildCartGoodsInfoForPreview中处理
     *
     * @param goodsList 商品列表
     */
    private void processActiveGoodsInfo(List<CartOrderPreviewResponseParam.CartGoodsInfo> goodsList) {
        // 由于单个商品的活动信息已经在buildCartGoodsInfoForPreview中处理，
        // 这里主要用于后续的批量计算逻辑，比如跨商品的活动计算
        // 目前暂时留空，后续可以根据需要扩展
    }

    /**
     * 转换购物车商品信息格式
     *
     * @param goodsList CartOrderPreviewResponseParam.CartGoodsInfo列表
     * @return CartResponseParam.CartGoodsInfo列表
     */
    private List<CartResponseParam.CartGoodsInfo> convertToCartGoodsInfo(List<CartOrderPreviewResponseParam.CartGoodsInfo> goodsList) {
        List<CartResponseParam.CartGoodsInfo> result = new ArrayList<>();

        for (CartOrderPreviewResponseParam.CartGoodsInfo goods : goodsList) {
            CartResponseParam.CartGoodsInfo cartGoods = new CartResponseParam.CartGoodsInfo();

            // 设置基本信息
            cartGoods.setGoodsId(goods.getGoodsId());
            cartGoods.setGoodsName(goods.getGoodsName());
            cartGoods.setGoodsImage(goods.getGoodsImage());
            cartGoods.setGoodsSkuId(goods.getGoodsSkuId());
            cartGoods.setGoodsSku(goods.getGoodsSku()); // 使用goodsSku作为goodsSpec
            cartGoods.setGoodsPrice(goods.getGoodsPrice());
            cartGoods.setGoodsNum(goods.getTotalNum());
            cartGoods.setGoodsTotalPrice(goods.getTotalPrice());

            // 设置活动信息
            cartGoods.setIsActiveGoods(goods.getIsActiveGoods());
            cartGoods.setActivePrice(goods.getActivePrice());
            cartGoods.setSetNum(goods.getSetNum());
            cartGoods.setActiveDiscount(goods.getActiveDiscount()); // 使用正确的字段
            cartGoods.setActiveInfo(goods.getActiveInfo());

            result.add(cartGoods);
        }

        return result;
    }

    /**
     * 获取购物车商品列表（用于预览）
     * 对应PHP版本的Cart::getList方法
     * 支持两种格式：
     * 1. 购物车预览：goodsId_goodsSkuId（从购物车表查询数量）
     * 2. 直接下单预览：goodsId_goodsSkuId_num（直接使用传入的数量）
     */
    private List<CartOrderPreviewResponseParam.CartGoodsInfo> getCartGoodsListForPreview(Long userId, String cartIds, Integer isGoodsType) {
        List<CartOrderPreviewResponseParam.CartGoodsInfo> goodsList = new ArrayList<>();

        try {
            // 如果指定了cartIds，则按ID过滤
            if (cartIds != null && !cartIds.trim().isEmpty()) {
                // 解析cartIds格式
                String[] cartIdArray = cartIds.split(",");
                
                for (String cartId : cartIdArray) {
                    String[] parts = cartId.split("_");
                    
                    if (parts.length == 2) {
                        // 格式1：goodsId_goodsSkuId - 购物车预览
                        try {
                            Long goodsId = Long.valueOf(parts[0]);
                            Long goodsSkuId = Long.valueOf(parts[1]);
                            
                            // 从购物车表查询商品信息
                            CartOrderPreviewResponseParam.CartGoodsInfo goodsInfo = getCartGoodsInfoFromCart(userId, goodsId, goodsSkuId, isGoodsType);
                            if (goodsInfo != null) {
                                goodsList.add(goodsInfo);
                            }
                        } catch (NumberFormatException e) {
                            log.warn("无效的购物车ID格式: {}", cartId);
                        }
                        
                    } else if (parts.length == 3) {
                        // 格式2：goodsId_goodsSkuId_num - 直接下单预览
                        try {
                            Long goodsId = Long.valueOf(parts[0]);
                            Long goodsSkuId = Long.valueOf(parts[1]);
                            Integer num = Integer.valueOf(parts[2]);
                            
                            // 直接构建商品信息，不查询购物车表
                            CartOrderPreviewResponseParam.CartGoodsInfo goodsInfo = buildDirectGoodsInfoForPreview(goodsId, goodsSkuId, num);
                            if (goodsInfo != null) {
                                goodsList.add(goodsInfo);
                            }
                        } catch (NumberFormatException e) {
                            log.warn("无效的直接下单ID格式: {}", cartId);
                        }
                    } else {
                        log.warn("无效的ID格式，需要2个或3个部分: {}", cartId);
                    }
                }
            } else {
                // 如果没有指定cartIds，查询用户所有购物车商品
                LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<Cart>()
                    .eq(Cart::getUserId, userId)
                    .eq(Cart::getIsGoodsType, isGoodsType != null ? isGoodsType : 10)
                    .eq(Cart::getIsDelete, 0);

                List<Cart> cartItems = cartMapper.selectList(queryWrapper.orderByDesc(Cart::getCreateTime));

                for (Cart cartItem : cartItems) {
                    CartOrderPreviewResponseParam.CartGoodsInfo goodsInfo = buildCartGoodsInfoForPreview(cartItem);
                    if (goodsInfo != null) {
                        goodsList.add(goodsInfo);
                    }
                }
            }

        } catch (Exception e) {
            log.error("获取购物车商品列表失败，用户ID: {}", userId, e);
            throw new CommonException("获取购物车商品列表失败：" + e.getMessage());
        }

        return goodsList;
    }

    /**
     * 从购物车表获取商品信息（购物车预览）
     */
    private CartOrderPreviewResponseParam.CartGoodsInfo getCartGoodsInfoFromCart(Long userId, Long goodsId, Long goodsSkuId, Integer isGoodsType) {
        try {
            // 查询购物车记录
            LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<Cart>()
                .eq(Cart::getUserId, userId)
                .eq(Cart::getGoodsId, goodsId)
                .eq(Cart::getGoodsSkuId, goodsSkuId)
                .eq(Cart::getIsGoodsType, isGoodsType != null ? isGoodsType : 10)
                .eq(Cart::getIsDelete, 0);

            Cart cartItem = cartMapper.selectOne(queryWrapper);
            if (cartItem == null) {
                log.warn("购物车中未找到商品，用户ID: {}, 商品ID: {}, SKU ID: {}", userId, goodsId, goodsSkuId);
                return null;
            }

            return buildCartGoodsInfoForPreview(cartItem);

        } catch (Exception e) {
            log.error("从购物车获取商品信息失败，用户ID: {}, 商品ID: {}, SKU ID: {}", userId, goodsId, goodsSkuId, e);
            return null;
        }
    }

    /**
     * 直接构建商品信息（直接下单预览）
     */
    private CartOrderPreviewResponseParam.CartGoodsInfo buildDirectGoodsInfoForPreview(Long goodsId, Long goodsSkuId, Integer num) {
        try {
            // 获取商品信息
            Goods goods = goodsMapper.selectById(goodsId);
            if (goods == null || goods.getIsDelete() == 1) {
                log.warn("商品不存在或已删除，商品ID: {}", goodsId);
                return null;
            }

            // 获取商品SKU信息
            GoodsSku goodsSku = goodsSkuMapper.selectById(goodsSkuId);
            if (goodsSku == null) {
                log.warn("商品SKU不存在，SKU ID: {}", goodsSkuId);
                return null;
            }

            // 获取商品图片
            String goodsImage = "";
            if (goods.getGoodsId() != null) {
                List<String> imageUrls = goodsImageMapper.getFileUrlByGoodsId(goods.getGoodsId());
                if (imageUrls != null && !imageUrls.isEmpty()) {
                    goodsImage = imageUrls.get(0);
                }
            }

            // 构建商品信息
            CartOrderPreviewResponseParam.CartGoodsInfo goodsInfo = new CartOrderPreviewResponseParam.CartGoodsInfo();
            goodsInfo.setGoodsId(goodsId);
            goodsInfo.setBarCode(goods.getBarCode());
            goodsInfo.setGoodsSkuId(goodsSkuId);
            goodsInfo.setGoodsName(goods.getGoodsName());
            goodsInfo.setGoodsImage(goodsImage);
            goodsInfo.setGoodsSku(goodsSku);
            goodsInfo.setGoodsPrice(goodsSku.getGoodsPrice());
            goodsInfo.setTotalNum(num);
            goodsInfo.setTotalPrice(goodsSku.getGoodsPrice().multiply(new BigDecimal(num)));

            // 设置默认值
            goodsInfo.setIsActiveGoods(0);
            goodsInfo.setActivePrice(BigDecimal.ZERO);
            goodsInfo.setSetNum(0);
            goodsInfo.setActiveInfo(null);
            goodsInfo.setActiveDiscount(new ArrayList<>());
            goodsInfo.setCouponMoney(BigDecimal.ZERO);
            goodsInfo.setPointsMoney(BigDecimal.ZERO);
            goodsInfo.setGradeMoney(BigDecimal.ZERO);
            goodsInfo.setTotalPayPrice(goodsInfo.getTotalPrice());

            // 检查是否是活动商品
            checkActiveGoodsInfo(goodsInfo, goodsId);

            return goodsInfo;

        } catch (Exception e) {
            log.error("构建直接下单商品信息失败，商品ID: {}, SKU ID: {}, 数量: {}", goodsId, goodsSkuId, num, e);
            return null;
        }
    }

    /**
     * 构建购物车商品信息（用于预览）
     * 对应PHP版本的Cart::getOrderGoodsList方法
     */
    private CartOrderPreviewResponseParam.CartGoodsInfo buildCartGoodsInfoForPreview(Cart cartItem) {
        try {
            // 获取商品信息
            Goods goods = goodsMapper.selectById(cartItem.getGoodsId());
            if (goods == null || goods.getIsDelete() == 1) {
                log.warn("商品不存在或已删除，商品ID: {}", cartItem.getGoodsId());
                return null;
            }

            // 获取商品SKU信息
            GoodsSku goodsSku = goodsSkuMapper.selectById(cartItem.getGoodsSkuId());
            if (goodsSku == null) {
                log.warn("商品SKU不存在，SKU ID: {}", cartItem.getGoodsSkuId());
                return null;
            }

            // 获取商品图片
            String goodsImage = "";
            if (goods.getGoodsId() != null) {
                List<String> imageUrls = goodsImageMapper.getFileUrlByGoodsId(goods.getGoodsId());
                if (imageUrls != null && !imageUrls.isEmpty()) {
                    goodsImage = imageUrls.get(0);
                }
            }

            // 构建购物车商品信息
            CartOrderPreviewResponseParam.CartGoodsInfo goodsInfo = new CartOrderPreviewResponseParam.CartGoodsInfo();
            goodsInfo.setGoodsId(cartItem.getGoodsId());
            goodsInfo.setBarCode(goods.getBarCode());
            goodsInfo.setGoodsSkuId(cartItem.getGoodsSkuId());
            goodsInfo.setGoodsName(goods.getGoodsName());
            goodsInfo.setGoodsImage(goodsImage);
            goodsInfo.setGoodsSku(goodsSku);
            goodsInfo.setGoodsPrice(goodsSku.getGoodsPrice());
            goodsInfo.setTotalNum(cartItem.getGoodsNum());
            goodsInfo.setTotalPrice(goodsSku.getGoodsPrice().multiply(new BigDecimal(cartItem.getGoodsNum())));
//            goodsInfo.setCartCreateTime(cartItem.getCreateTime() != null ? cartItem.getCreateTime().getTime() : System.currentTimeMillis());

            // 设置默认值
            goodsInfo.setIsActiveGoods(0);
            goodsInfo.setActivePrice(BigDecimal.ZERO);
            goodsInfo.setSetNum(0);
            goodsInfo.setActiveInfo(null);
            goodsInfo.setActiveDiscount(new ArrayList<>());
            goodsInfo.setCouponMoney(BigDecimal.ZERO);
            goodsInfo.setPointsMoney(BigDecimal.ZERO);
            goodsInfo.setGradeMoney(BigDecimal.ZERO);
            goodsInfo.setTotalPayPrice(goodsInfo.getTotalPrice());

            // 检查是否是活动商品（在设置默认值之后）
            checkActiveGoodsInfo(goodsInfo, cartItem.getGoodsId());

            return goodsInfo;

        } catch (Exception e) {
            log.error("构建购物车商品信息失败，cartItem: {}", cartItem, e);
            return null;
        }
    }

    /**
     * 检查活动商品信息
     * 对应PHP版本的Cart::discount_active方法
     */
    private void checkActiveGoodsInfo(CartOrderPreviewResponseParam.CartGoodsInfo goodsInfo, Long goodsId) {
        try {
            // 1. 先查询活动商品表，看该商品是否参加活动
            List<DiscountActiveGoods> activeGoodsList = discountActiveGoodsMapper.selectList(
                new LambdaQueryWrapper<DiscountActiveGoods>().eq(DiscountActiveGoods::getGoodsId, goodsId)
            );

            if (!activeGoodsList.isEmpty()) {
                // 2. 遍历该商品参加的活动，查找有效的活动
                for (DiscountActiveGoods activeGoods : activeGoodsList) {
                    Long discountId = activeGoods.getDiscountId();

                        // 3. 用活动ID去查找有效的活动
                        DiscountActive active = discountActiveMapper.selectById(discountId);
                        if (active != null && active.getIsDelete() == 0 && active.getStatus() == 10) {
                            // 设置活动基本信息
                            goodsInfo.setIsActiveGoods(1);
                            goodsInfo.setActiveInfo(active);

                            // 查询活动规格（对应PHP的ActiveSpecModel查询）
                            List<DiscountActiveSpec> activeSpecs = discountActiveSpecMapper.selectList(
                                new LambdaQueryWrapper<DiscountActiveSpec>()
                                    .eq(DiscountActiveSpec::getDiscountId, discountId)
                                    .orderByAsc(DiscountActiveSpec::getNum)
                            );

                            // 转换为List<Object>类型
                            List<Object> activeDiscountList = new ArrayList<>();
                            for (DiscountActiveSpec spec : activeSpecs) {
                                Map<String, Object> specMap = new HashMap<>();
                                specMap.put("id", spec.getId());
                                specMap.put("discountId", spec.getDiscountId());
                                specMap.put("num", spec.getNum());
                                specMap.put("price", spec.getPrice());
                                activeDiscountList.add(specMap);
                            }
                            goodsInfo.setActiveDiscount(activeDiscountList);

                            // 设置起订量
                            goodsInfo.setSetNum(active.getSetNum() != null ? active.getSetNum() : 0);

                            // 计算活动价格（对应PHP的活动价格计算逻辑）
                            if (goodsInfo.getTotalNum() >= goodsInfo.getSetNum()) {
                                // 满足起订量，查找合适的阶梯价格
                                DiscountActiveSpec matchedSpec = null;
                                for (int i = activeSpecs.size() - 1; i >= 0; i--) {
                                    DiscountActiveSpec spec = activeSpecs.get(i);
                                    if (goodsInfo.getTotalNum() >= spec.getNum()) {
                                        matchedSpec = spec;
                                        break; // 找到第一个满足条件的规格（向下取整）
                                    }
                                }

                                if (matchedSpec != null) {
                                    goodsInfo.setActivePrice(matchedSpec.getPrice());
                                    goodsInfo.setTotalPrice(matchedSpec.getPrice().multiply(new BigDecimal(goodsInfo.getTotalNum())));
                                    goodsInfo.setTotalPayPrice(goodsInfo.getTotalPrice());
                                } else {
                                    // 如果没有找到匹配的规格，使用原价
                                    goodsInfo.setActivePrice(goodsInfo.getGoodsPrice());
                                }
                            } else {
                                // 未满足起订量
                                goodsInfo.setIsActiveGoods(2);
                                goodsInfo.setActivePrice(goodsInfo.getGoodsPrice()); // 使用原价
                                goodsInfo.setTotalPrice(goodsInfo.getGoodsPrice().multiply(new BigDecimal(goodsInfo.getTotalNum())));
                                goodsInfo.setTotalPayPrice(goodsInfo.getTotalPrice());
                            }

                            // 找到有效的活动后，跳出循环
                            break;
                        }
                    }
            }
        } catch (Exception e) {
            log.warn("检查活动商品信息失败，商品ID: {}", goodsId, e);
        }
    }

    /**
     * 获取满赠商品列表（对应PHP的marketGoodsList方法）
     *
     * @param orderPayPrice 订单支付金额
     * @param marketGoodsIds 用户选择的赠品商品ID列表（格式：goodsId_num,多个用逗号分隔）
     * @return 满赠商品列表
     */
    private List<Object> getMarketGoodsList(BigDecimal orderPayPrice, String marketGoodsIds) {
        List<Object> marketGoodsList = new ArrayList<>();

        try {
            // 获取满赠设置
            FullFreeSettingVo fullFreeSetting = storeSettingService.getFullFreeSetting();
            if (fullFreeSetting == null || fullFreeSetting.getIsOpen() == null || fullFreeSetting.getIsOpen() != 1) {
                // 未开启满赠功能
                return marketGoodsList;
            }

            // 检查订单金额是否达到满赠条件
            BigDecimal fullFreeMoney = fullFreeSetting.getMoney();
            if (fullFreeMoney == null || orderPayPrice.compareTo(fullFreeMoney) < 0) {
                // 订单金额不足
                return marketGoodsList;
            }

            List<Long> goodsIds = new ArrayList<>();
            Map<Long, Integer> goodsNumMap = new HashMap<>();

            if (marketGoodsIds != null && !marketGoodsIds.trim().isEmpty()) {
                // 用户选择了特定的赠品
                String[] marketGoodsIdArray = marketGoodsIds.split(",");

                // 校验赠品选择类型（单选/混选）
                Integer isGoodsType = fullFreeSetting.getIsGoodsType();
                if (isGoodsType == null || isGoodsType == 0) { // 单选
                    if (marketGoodsIdArray.length > 1) {
                        log.error("当前赠品仅支持单选！选择了 {} 个商品", marketGoodsIdArray.length);
                        throw new CommonException("当前赠品仅支持单选！");
                    }
                }

                // 解析用户选择的赠品
                int totalNum = 0;
                for (String marketGoodsId : marketGoodsIdArray) {
                    String[] parts = marketGoodsId.split("_");
                    if (parts.length >= 2) {
                        Long goodsId = Long.parseLong(parts[0]);
                        Integer num = Integer.parseInt(parts[1]);

                        goodsIds.add(goodsId);
                        goodsNumMap.put(goodsId, num);
                        totalNum += num;
                    }
                }

                // 校验赠品数量不超过限制
                Integer maxNumber = fullFreeSetting.getNumber();
                if (maxNumber != null && totalNum > maxNumber) {
                    log.error("已超出赠品数量，已选 {} 个，限制 {} 个", totalNum, maxNumber);
                    throw new CommonException("已超出赠品数量，请修改赠品数量！");
                }
            } else {
                // 使用默认的赠品配置
                List<FullFreeSettingVo.NotInGoods> notinGoods = fullFreeSetting.getNotinGoods();
                if (notinGoods != null && !notinGoods.isEmpty()) {
                    for (FullFreeSettingVo.NotInGoods goods : notinGoods) {
                        goodsIds.add(goods.getGoodsId());
                        goodsNumMap.put(goods.getGoodsId(), 0); // 默认数量为0
                    }
                }
            }

            if (!goodsIds.isEmpty()) {
                // 获取商品详细信息
                List<Goods> goodsList = goodsMapper.selectBatchIds(goodsIds);
                if (goodsList != null && !goodsList.isEmpty()) {
                    for (Goods goods : goodsList) {
                        Map<String, Object> goodsInfo = new HashMap<>();

                        // 基本信息
                        goodsInfo.put("goodsId", goods.getGoodsId());
                        goodsInfo.put("goodsName", goods.getGoodsName());
                        goodsInfo.put("sellingPoint", goods.getSellingPoint());

                        // 商品图片
                        List<String> imageUrls = goodsImageMapper.getFileUrlByGoodsId(goods.getGoodsId());
                        goodsInfo.put("image", imageUrls.isEmpty() ? "" : imageUrls.get(0));

                        // 赠品商品没有SKU，价格直接设为0
                        // 赠品的价格永远是0，不需要查询SKU信息
                        goodsInfo.put("goodsPrice", BigDecimal.ZERO);
                        goodsInfo.put("linePrice", BigDecimal.ZERO);
                        goodsInfo.put("goodsSales", 0);

                        goodsInfo.put("totalNum", goods.getGiftStockNum()>0?goods.getGiftStockNum():0);

                        marketGoodsList.add(goodsInfo);
                    }
                }
            }

        } catch (CommonException e) {
            // 业务异常直接抛出
            throw e;
        } catch (Exception e) {
            log.error("获取满赠商品列表失败", e);
            // 返回空列表，不影响正常购物流程
        }

        return marketGoodsList;
    }

    /**
     * 处理订单赠品商品
     * 将赠品商品添加到订单商品表中
     *
     * @param orderId 订单ID
     * @param marketGoodsIds 赠品商品ID列表，格式：商品ID_无意义数字_数量，多个用逗号分隔
     * @param createTime 创建时间戳
     */
    private void processMarketGoodsForOrder(Integer orderId, String marketGoodsIds, long createTime) {
        if (marketGoodsIds == null || marketGoodsIds.trim().isEmpty()) {
            return;
        }

        String[] marketGoodsArray = marketGoodsIds.split(",");
        for (String marketGoods : marketGoodsArray) {
            String[] parts = marketGoods.trim().split("_");
            if (parts.length != 3) {
                log.warn("赠品商品格式错误，跳过: {}", marketGoods);
                continue;
            }

            try {
                Long goodsId = Long.parseLong(parts[0]);
                Integer quantity = Integer.parseInt(parts[2]);

                if (quantity <= 0) {
                    log.warn("赠品商品数量无效，跳过: {}", marketGoods);
                    continue;
                }

                // 查询赠品商品信息
                Goods goods = goodsMapper.selectById(goodsId);
                if (goods == null || goods.getIsDelete() == 1) {
                    log.warn("赠品商品不存在或已删除，跳过: {}", goodsId);
                    continue;
                }

                if (goods.getIsType() != 20) {
                    log.warn("商品不是赠品类型，跳过: {}", goodsId);
                    continue;
                }

                // 创建赠品订单商品记录
                OrderGoods og = new OrderGoods();
                og.setOrderId(orderId.intValue());
                og.setGoodsId(goodsId.intValue());
                og.setGoodsName(goods.getGoodsName());
                og.setGoodsSkuId(0); // 赠品没有SKU
                og.setGoodsSkuSpec("赠品");
                og.setSpecSkuId("0");
                og.setGoodsAttr("赠品");
                og.setContent("满赠活动赠品");
                og.setGoodsPrice(BigDecimal.ZERO); // 赠品价格为0
                og.setGoodsMoney(BigDecimal.ZERO); // 赠品金额为0
                og.setTotalNum(quantity);
                og.setTotalPrice(BigDecimal.ZERO); // 赠品总价为0
                og.setTotalPayPrice(BigDecimal.ZERO); // 赠品支付价为0
                og.setDiscountActivePrice(BigDecimal.ZERO); // 赠品活动价为0
                og.setIsType(20);
                // 设置图片
                List<GoodsImage> goodsImages = goodsImageMapper.selectList(
                    new LambdaQueryWrapper<GoodsImage>().eq(GoodsImage::getGoodsId, goodsId));
                if (goodsImages != null && !goodsImages.isEmpty()) {
                    og.setImageId(goodsImages.get(0).getImageId().intValue());
                }

                // 设置其他默认值
                og.setIsOrderExpress(10); // 未发货（赠品一般不需要发货）
                og.setIsComment(0);
                og.setCouponMoney(BigDecimal.ZERO);
                og.setPointsMoney(BigDecimal.ZERO);
                og.setPointsNum(0);
                og.setPointsBonus(0);
                og.setIsDelete(0);
                og.setCreateTime(createTime);

                // 保存赠品到订单商品表
                orderGoodsService.save(og);

                log.info("订单 {} 添加赠品商品: {} x {}", orderId, goods.getGoodsName(), quantity);

            } catch (NumberFormatException e) {
                log.warn("赠品商品参数格式错误，跳过: {}", marketGoods);
            } catch (Exception e) {
                log.error("处理赠品商品失败: {}", marketGoods, e);
            }
        }
    }

    /**
     * 获取已发货数量
     * @param orderId 订单ID
     * @param goodsId 商品ID
     * @return 已发货数量
     */
    private Integer getDeliveredQuantity(Integer orderId, Integer goodsId) {
        try {
            // 查询该订单的所有物流记录
            List<OrderExpress> orderExpressList = storeOrderMapper.selectOrderExpress(Long.valueOf(orderId));
            if (orderExpressList == null || orderExpressList.isEmpty()) {
                return 0;
            }

            Integer totalDelivered = 0;

            for (OrderExpress express : orderExpressList) {
                if (express.getGoodsId() != null && express.getGoodsNum() != null) {
                    try {
                        log.debug("解析物流记录，orderExpressId: {}, goodsId: {}, goodsNum: {}",
                                express.getOrderExpressId(), express.getGoodsId(), express.getGoodsNum());

                        // 解析商品ID列表
                        List<String> goodsIdList = parseJsonArray(express.getGoodsId());

                        // 解析商品数量映射
                        Map<String, Integer> goodsNumMap = parseJsonObject(express.getGoodsNum());

                        // 查找指定商品的发货数量
                        String targetGoodsId = String.valueOf(goodsId);
                        if (goodsIdList.contains(targetGoodsId) && goodsNumMap.containsKey(targetGoodsId)) {
                            totalDelivered += goodsNumMap.get(targetGoodsId);
                            log.debug("找到商品发货记录，goodsId: {}, quantity: {}", targetGoodsId, goodsNumMap.get(targetGoodsId));
                        }
                    } catch (Exception e) {
                        log.warn("解析物流记录JSON失败，orderExpressId: {}, goodsId: {}, goodsNum: {}, error: {}",
                                express.getOrderExpressId(), express.getGoodsId(), express.getGoodsNum(), e.getMessage());
                    }
                }
            }

            return totalDelivered;
        } catch (Exception e) {
            log.error("查询已发货数量失败，orderId: {}, goodsId: {}", orderId, goodsId, e);
            return 0;
        }
    }

    /**
     * 解析JSON数组，支持多种格式
     * @param jsonStr JSON字符串
     * @return 字符串列表
     * @throws Exception 解析异常
     */
    private List<String> parseJsonArray(String jsonStr) throws Exception {
        if (jsonStr == null || jsonStr.trim().isEmpty()) {
            return new ArrayList<>();
        }

        String trimmed = jsonStr.trim();

        // 如果已经是数组格式 ["1","2","3"]
        if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
            try {
                return objectMapper.readValue(trimmed, new TypeReference<List<String>>() {});
            } catch (Exception e) {
                log.warn("标准JSON数组解析失败，尝试其他格式: {}", trimmed);
            }
        }

        // 如果是逗号分隔的字符串 "1,2,3"
        if (!trimmed.startsWith("[") && trimmed.contains(",")) {
            String[] parts = trimmed.split(",");
            List<String> result = new ArrayList<>();
            for (String part : parts) {
                result.add(part.trim());
            }
            return result;
        }

        // 如果是单个值且没有逗号
        if (!trimmed.startsWith("[") && !trimmed.contains(",")) {
            List<String> result = new ArrayList<>();
            result.add(trimmed);
            return result;
        }

        // 最后的尝试：直接用标准JSON解析
        return objectMapper.readValue(trimmed, new TypeReference<List<String>>() {});
    }

    /**
     * 解析JSON对象，支持多种格式
     * @param jsonStr JSON字符串
     * @return 字符串到整数的映射
     * @throws Exception 解析异常
     */
    private Map<String, Integer> parseJsonObject(String jsonStr) throws Exception {
        if (jsonStr == null || jsonStr.trim().isEmpty()) {
            return new HashMap<>();
        }

        String trimmed = jsonStr.trim();

        // 如果已经是对象格式 {"1":2,"3":4}
        if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
            try {
                return objectMapper.readValue(trimmed, new TypeReference<Map<String, Integer>>() {});
            } catch (Exception e) {
                log.warn("标准JSON对象解析失败，尝试其他格式: {}", trimmed);
            }
        }

        // 如果是其他格式，尝试直接解析为Map
        try {
            return objectMapper.readValue(trimmed, new TypeReference<Map<String, Integer>>() {});
        } catch (Exception e) {
            log.warn("JSON对象解析失败: {}", trimmed);
            return new HashMap<>();
        }
    }
} 